我使用结构创建了一个单链表。该结构包含一个整数和一个结构指针next
。我按升序对列表进行排序。我将head
指针传递给排序函数。排序算法运行正常,但是在排序后将相同的head
传递给显示函数时,不会反映更改。我也尝试使用指针指针,如果这是推荐的解决方案。以下是我的程序的示例代码,它重现了相同的错误: -
#include<iostream>
class List
{
public:
struct ListNode
{
int Number;
ListNode *next;
}*head;
int TotalNodes;
List()
{
head = NULL;
TotalNodes = 0;
}
void CreateList(int Number)
{
ListNode *newNode, *nodePtr;
newNode = new ListNode;
newNode->Number = Number;
newNode->next = NULL;
++TotalNodes;
if(!head)
{
head = newNode;
}
else
{
nodePtr = head;
while(nodePtr->next) nodePtr = nodePtr->next;
nodePtr->next = newNode;
}
}
void SortList(ListNode *HEAD, int NODECOUNT)
{
int i, Passes = (((NODECOUNT * NODECOUNT) + NODECOUNT) / 2);
ListNode *nodePtr, *lastNode, *lastNodePREV;
for(i=0; i <= Passes; i++)
{
lastNode = HEAD;
nodePtr = lastNode->next;
while(nodePtr->next && lastNode->Number < nodePtr->Number)
{
lastNodePREV = lastNode;
lastNode = lastNode->next;
nodePtr = nodePtr->next;
}
if(lastNode == HEAD)
{
HEAD->next = nodePtr->next;
nodePtr->next = HEAD;
HEAD = nodePtr;
}
else
{
lastNodePREV->next = nodePtr;
lastNode->next = nodePtr->next;
nodePtr->next = lastNode;
}
}
nodePtr = HEAD;
while(nodePtr)
{
std::cout<<" "<<nodePtr->Number;
nodePtr = nodePtr->next;
}
}
void Display(ListNode *HEAD)
{
ListNode *nodePtr;
nodePtr = HEAD;
while(nodePtr)
{
std::cout<<" "<<nodePtr->Number;
nodePtr = nodePtr->next;
}
}
};
int main()
{
List list;
for(int i=10; i >= 0; i--)
{
list.CreateList(i);
}
list.Display(list.head); //before sorting
std::cout<<"\n\n";
list.SortList(list.head, list.TotalNodes);
std::cout<<"\n\n";
list.Display(list.head); //after sorting
return 0;
}
上述计划的输出: -
10 9 8 7 6 5 4 3 2 1 0
0 1 2 3 4 5 6 7 8 9 10
10
我认为这与排序功能有关,可以创建列表的副本,但是我该如何编辑同一个列表?
谢谢。
PS: - 我也试过返回指针,但后来我收到了关于无法从ListNode*
转换为List*
的错误信息: -
ListNode* List::SortList(...)
{
....
....
return HEAD;
}
在main()
中称为
list.head = list.SortList(...);
PPS: - 此问题的解决方案是在函数*&HEAD
的参数中使用*HEAD
而不是Sortlist()
PPPS: - 我想澄清一下我使用pass-by-reference的另一件事,因为我在实际程序中处理了几个链表。这只是它的一个例子。