【发布时间】:2021-12-09 15:29:07
【问题描述】:
我一直在尝试在不使用交换节点的情况下解决单链表中的选择排序问题。使用临时列表存储节点并为当前列表分配一个新列表
//my addlastnode function
void AddLastNODE(LIST &mylist, NODE *p)
{
//Check the list is empty or not
if(isEmpty(mylist))
mylist.pHead = mylist.pTail = p;
else
mylist.pTail->pNext = p;
mylist.pTail = p;
}
void selectionSort(LIST &mylist)
{
//Initialize a temp list to store nodes
LIST mylisttemp;
IntList(mylisttemp);
//Create node
NODE *p;
NODE *i;
//Create min node
NODE *min;
//Check if list is empty or has one node
if(mylist.pHead == mylist.pTail)
return;
//Traverse the list till the last node
for(p=mylist.pHead; p->pNext!=NULL && p!=NULL; p = p->pNext)
{
min=p;
for(i=p->pNext; i!=NULL;i=i->pNext)
{
////Find the smallest data in list
if(i->data < min->data)
min=i;
}
////Add the smallest to a new list
AddLastNODE(mylisttemp, min);
}
//Fill the current list to the new list
if(!isEmpty(mylisttemp))
mylist = mylisttemp;
}
【问题讨论】:
-
您不能只将节点添加到新列表中而不将其从旧列表中彻底删除:在两个列表中拥有相同的节点而只有一个与
.next链接几乎是不可能的。请注意,在迭代列表时删除列表中的节点并不是那么简单。 -
@JoëlHecht 我明白了,谢谢
标签: c++ c algorithm data-structures linked-list