下面是代码,
#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-> NULL1-> 2-> 6-> 3-> NULL
对于链接列表2,输出如下所示6-> 2-> 1-> 3-> NULL3-> 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->无止境
[交换两个节点a
和b
时,还必须固定到达a
和到达b
的指针。例如