C++ 使用指针对单链接列表进行排序
我试图通过只操作指针而不操作键来使用冒泡排序对单链接列表进行排序 下面的代码被困在for循环和无限循环中。我不明白这是为什么。谁能向我解释一下为什么没有找到名单的末尾C++ 使用指针对单链接列表进行排序,c++,bubble-sort,singly-linked-list,C++,Bubble Sort,Singly Linked List,我试图通过只操作指针而不操作键来使用冒泡排序对单链接列表进行排序 下面的代码被困在for循环和无限循环中。我不明白这是为什么。谁能向我解释一下为什么没有找到名单的末尾 Node* sort_list(Node* head) { Node * temp; Node * curr; for(bool didSwap = true; didSwap; ) { didSwap = false; for(curr = head; cu
Node* sort_list(Node* head)
{
Node * temp;
Node * curr;
for(bool didSwap = true; didSwap; ) {
didSwap = false;
for(curr = head; curr->next != NULL; curr = curr->next) {
if(curr->key > curr->next->key) {
temp = curr;
curr = curr->next;
curr->next = temp;
didSwap = true;
}
cout << curr->next->key << endl;
}
}
return head;
Node*排序列表(Node*head)
{
节点*温度;
节点*curr;
for(bool didSwap=true;didSwap;){
didSwap=false;
对于(curr=head;curr->next!=NULL;curr=curr->next){
如果(当前->键>当前->下一步->键){
温度=电流;
当前=当前->下一步;
当前->下一步=温度;
didSwap=true;
}
cout next->key您有以下问题:
让您有一个包含三个成员的列表:ptr1->ptr2->ptr3
。在交换之前,您设置了以下指针:curr=ptr1;curr->next=ptr2;curr->next=ptr2;curr->next=ptr3
。执行交换时,您将收到curr=ptr2;curr->next=ptr1;curr->next=ptr2
例如,您丢失了ptr3。您需要使用以下内容更改内环代码:
temp = curr;
temp->next = curr->next->next; // Save ptr3
curr = curr->next;
curr->next = temp;
didSwap = true;
您要交换的字段是值
。但是,如果您交换节点
,则下一个
字段将发生更改,问题变得更复杂,您需要保持下一个
字段正确。总之,更改值
是一个简单而好的方法。逻辑错误,您正在创建infinite循环,代码如下-
temp = curr;
curr = curr->next;
curr->next = temp;
一、 当前值的e next\u指向当前值,因此curr->next将始终为curr,并且永远不会为空
接下来,您应该使用上一个指针来修复列表,因为您的列表可以在一个方向上遍历。因此,请考虑-
如果A->B->C->NULL;并且您进行了C和B交换,那么新列表仍将指向A->B,并且下一次迭代将是错误的……因为您没有修改上一次的下一次
因此,另一个实现可能是-
Node* sort_list(Node* head) {
Node * curr;
Node * prev;
for(bool didSwap = true; didSwap; ) {
didSwap = false;
prev = head;
for(curr = head; curr->next != NULL; curr = curr->next) {
if(curr->key > curr->next->key) {
if (head == curr) {
head = curr->next;
curr->next = head->next;
head->next = curr;
prev = head;
} else {
prev->next = curr->next;
curr->next = prev->next->next;
prev->next->next = curr
}
didSwap = true;
} else if (head != curr) {
prev = prev->next;
}
//cout << curr->next->key << endl; // <- this may cause crash if curr->next now points to NULL; (i,e last element)
}
}
return head;
}
Node*排序列表(Node*head){
节点*curr;
节点*prev;
for(bool didSwap=true;didSwap;){
didSwap=false;
prev=头部;
对于(curr=head;curr->next!=NULL;curr=curr->next){
如果(当前->键>当前->下一步->键){
如果(水头==当前){
head=当前->下一步;
当前->下一步=头部->下一步;
head->next=curr;
prev=头部;
}否则{
上一个->下一个=当前->下一个;
当前->下一步=上一步->下一步->下一步;
上一个->下一个->下一个=当前
}
didSwap=true;
}否则如果(头!=当前){
上一个=上一个->下一个;
}
//cout next->key我想你可能应该说明你在节点
列表的末尾。curr->next->next
如果你在最后一个节点
元素上,就会崩溃。我正在尝试在不更改任何值的情况下完成排序。只有指针。请不要只发布代码答案。解释你正在做什么来解决这个问题这个问题。这篇文章也可以做一些代码格式化
node *sorted_list(node *head) {
node *index1,*index2;
for(index1=head;index1->next!=NULL;index1=index1->next) {
for(index2=index1->next;index2!=NULL;index2=index2->next) {
if(index1->data>index2->data) {
int temp=index1->data;
index1->data=index2->data;
index2->data=temp;
}
}
}
return head;
}