2

我对无限循环很生气,你认为什么是合适的解决方案?

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++;
    }
  }
}

我尝试在 for 循环之前和之后增加计数并使用 while- 的许多条件,但没有结果

4

2 回答 2

3

一个更简单的滑过链表的方法是这样的:

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

并滑动到倒数第二个项目(确保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);
    }
  }
}

尽管排序链表通常不是最好的方法(除非您正在执行合并)。

于 2013-10-03T21:11:55.703 回答
2

问题是你正在循环直到计数并且你在循环的每次运行中增加计数//删除行计数++以避免删除无限循环

于 2013-10-03T21:11:22.133 回答