在 c++ 中对链表进行排序

Sorting a linked list in c++

本文关键字:排序 链表 c++      更新时间:2023-10-16

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

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 循环之前和之后使用许多条件,但没有结果

滑动

链表的一种更简单的方法是这样的:

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

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

问题是您正在循环直到计数,并且在每次运行循环//删除行计数++以避免删除无限循环时都会增加计数