2013-10-03 97 views
1

我对无限循环感到生气,你认为什么是合适的解决方案?在C++中对链表进行排序

void sorting() { 
    node * temphead = head; 
    node * tempnode = NULL; 

    for (int i=0; i<count; i++) { 
    for (int j=0; j<count-i; j++) { 
     if (temphead->data > temphead->next->data) { 
     tempnode = temphead; 
     temphead = temphead->next; 
     temphead->next = tempnode; 
     } 

     temphead=temphead->next; 
     count++; 
    } 
    } 
} 

我试图增量次数和使用前,用while-很多条件,后为没有结果环路

回答

3

一个简单的方法,通过一个链表下滑是这样的:

for (node *current = head; current != nullptr; current = current->next) { 
    // This will run through all of the nodes until we reach the end. 
} 

,滑TH Ë倒数第二个项目(确保node->next存在)看起来是这样的:

for (node *current = head; current->next != nullptr; current = current->next) { 
    // Go through all of the nodes that have a 'next' node. 
} 

如果要统计有多少项目在一个链表,你做这样的事情:

int count = 0; 
for (node *current = head; current != nullptr; current = current->next) { 
    count = count + 1; 
} 

所以就像你有一个以上的选择类型排序是这样的:

for (node *index = head; index->next != nullptr; index = index->next) { 
    for (node *selection = index->next; selection != nullptr; selection = selection->next) { 
    if (index->data > selection->data) { 
     swap(index->data, selection->data); 
    } 
    } 
} 

虽然排序链表一般是不会去(除非你执行合并)的最佳方式。

+0

我明白了,这就是我真正需要的,但是当我在屏幕上仍然没有排序:(。谢谢你的建议。 –

+0

嗯..我从内存,我会尽快调试它并重新发布工作版本 – sircodesalot

+0

修正了与其交换节点本身,我只是交换了数据。 – sircodesalot

2

问题是您的循环,直到计数和你在的每一个运行递增计数循环//删除行数++避免删除无限循环

+0

看起来他想循环遍历列表(按count)并在同一个循环中对元素进行计数:) – Slava

+0

应该有重复计数变量,例如count1(或者更好地重新命名为size和count),如果您尝试像什么@Slava说 –

+0

删除计数不起作用 –