链接列表未反转



Bellow,我有一些代码应该显示一个链表,反转它,然后显示现在反转的链表,但它似乎永远不会显示。我唯一的猜测是,不知何故,链接列表正在变为空。我做错了什么?反向函数和应该显示反向数组的函数都运行了,但之后没有视觉输出。

#include <iostream>
using namespace std;
class Node{
public:// creation of a simple Node class
int data;
Node* next;

};
class LinkedList{
public:
Node* head;
LinkedList() { head = NULL; }
void append( int x){
Node* temp = new Node;// allocate new node
Node* end = head;//used later

temp->data = x;//giving the node data
temp->next = NULL;//since this node will be last make the next of it NULL

if(head == NULL){// if list is empty then set new Node as the head
head = temp;
return;
}
while(end->next != NULL){// go until the last node
end = end->next;
}
end->next = temp;// change the next of the last node to the new node.
}
void reverse(){
Node* current = head;
Node* next = NULL;
Node* prev = NULL;

while(current != NULL){
next = current->next;// Store next
current->next = prev;// Reverse current node's pointer

prev = current;// Move pointers one position ahead.
current = next;
}

head = prev;
}
void display(){
while(head != NULL){// print data while not out of bounds
cout<<" "<<head->data;
head = head->next;
}
}
};


int main() {
LinkedList list;
list.append(1);
list.append(10);
list.append(32);
list.append(64);
list.append(102);
list.append(93);
list.display();
cout<<endl;
list.reverse();
cout<<"list reversed"<<endl;
list.display();
cout<<"reverse display ran"<<endl;

事实证明,这是我的疏忽,我应该设置一个表示head的临时变量,在我当前的程序中,我正在更改head引用的内容,以便在链表中循环,因此一旦head到达列表末尾,就将其设置为null。写显示函数的正确方法是:

void display(){
Node* temp = head;
while(temp != NULL){// print data while not out of bounds
cout<<" "<<temp->data;
temp = temp->next;
}
}

感谢用户Retired Ninja提醒我存在调试器。

相关内容

  • 没有找到相关文章

最新更新