【发布时间】:2020-03-21 20:28:22
【问题描述】:
下面是代码,
#include<bits/stdc++.h>
using namespace std;
class node{
public:
int data;
node * next;
node(){
this->next = NULL;
}
node(int data){
this->data = data;
this->next = NULL;
}
};
class linkedList{
public:
node * head;
node * tail;
linkedList(){
this->head = NULL;
}
void getTail(node *& t){
t = head;
while(t->next != NULL){
t = t->next;
}
}
void insertAtEnd(int data){
node * newNode = new node(data);
if(head == NULL){
head = newNode;
return;
}
node * temp = head;
while(temp->next != NULL){
temp = temp->next;
}
temp->next = newNode;
}
void print(){
node * temp = head;
while(temp != NULL){
printf("%d->", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
void swap(node *& a, node *& b){
node * temp = a;
a = b;
b = temp;
}
void swapNode(node ** start, node ** end){
swap(*start, *end);
swap(((*start)->next), (*end)->next);
}
};
int main(){
///////////////////////////////////////
linkedList * ll1 = new linkedList(); //
ll1->insertAtEnd(6); //
ll1->insertAtEnd(2); //
ll1->insertAtEnd(1); //
ll1->insertAtEnd(3); //
ll1->print(); /////////////////////
ll1->swapNode(&ll1->head, &ll1->head->next->next->next);// ----> This is working
//////////////////////////////////////////////////////////
linkedList * ll2 = new linkedList();
ll2->insertAtEnd(6);
ll2->insertAtEnd(2);
ll2->insertAtEnd(1);
ll2->insertAtEnd(3);
ll2->print();
node * tail;
ll2->getTail(tail);
ll2->swapNode(&ll2->head, &tail); // This is not working // Going into a infinte loop
ll2->print();
}
当尾节点存储在其他变量中时,似乎存在一个永远循环。 当通过使用下一个指针遍历到最后一个给出尾节点时代码正在工作。
所以,下面是链表的第一个示例的输出,即 6->2->1->3->NULL 1->2->6->3->空
对于链表#2,输出如下 6->2->1->3->NULL 3->2->1->3->2->1->3->2->1->3->2->1->3->2->1->3->2- >1->3->2->1->3->2->1->3->2->1->3->2->1->3->2->1->3 ->2->1->3->2->1->3->2->1->3->2->1->3->2->1->3->2-> 1->3->2->1->3->2->1->3->2->1->3->2->1->3->2->1->3- >2->1->3->2->1->3->2->1->3->2->1->3->2->1->3->2->1 ->3->2->1->3->2->1->3->2->1->3->2->1->3->2->1->3-> 2->1->3->2->1->3->2->1->3->2->1->3->2->1->3->2->1- >3->2->1->3->2->1->3->2->1->3->2->1->3->2->1->3->2 ->1->3->2->1->3->2->1->3->2->1->3->2->1->3->2->1-> 3->2->1->3->2->1->3->2->1->3->2->1->3->2->1->3->2- >1->3->2->1->3->2->1->3->2->1->3->2->1->3->2->1->3 ->2->1->3->2->1->3->2->1->3->2->1->3->2->1->3->2-> 1->3->2->1->3->2->1->3->2->1->3->2->1->3->2->1->3- >2->1->3->2->没有结局
【问题讨论】:
-
第一个例子,交换后列表不应该变成
3->2->1->6->NULL,而不是1->2->6->3->NULL吗?
标签: c++ pointers data-structures linked-list singly-linked-list