因此,我尝试将java版本的链表移植到c++,但使用指针指向正确的对象时遇到了很大困难。移除遍历和反向遍历的目标是简单地按顺序打印出链表的值,然后按相反的顺序打印。这是代码。我之所以发布大部分内容而不是某些部分,是因为我相信你需要它的上下文
控制台输出:他们是平等的已删除5穿过-858993460
它打印出它们是相等的,因为它在remove(data)中while循环的第一次迭代时立即中断。
#include <iostream>
#include <string>
#include <string.h>
using namespace std;
class Node{
public:
int data;
Node *pNext;
Node();
Node(int x);
};
Node::Node(){
data = NULL;
pNext = NULL;
}
Node::Node(int x){
data = x;
pNext = NULL;
}
class List{
private:
Node *head = NULL;
public:
void insert(int data){
Node temp(data);
temp.pNext = head;
head = &temp;
}
Node removeHead(){
if (head != NULL){
Node *temp = head;
head = head->pNext;
return *temp;
}
else{
cout << "Empty List" << endl;
}
return NULL;
}
Node remove(int data){
Node *previousLink = head;
Node *currentLink = head;
while (currentLink->data != data){
if (currentLink == currentLink->pNext){
cout << "They are equal" << endl;
break;
}
previousLink = currentLink;
if (currentLink->data == NULL)
currentLink = currentLink->pNext;
cout << "Current " << currentLink->data << " Previous "
<< previousLink->data <<endl;
}
if (head->data == data){
head = head->pNext;
}
else{
previousLink->pNext = currentLink->pNext;
}
return *currentLink;
}
void traverse(){
traverse(head);
}
void reverseTraverse(){
reverseTraverse(head);
}
private:
void traverse(Node *link){
cout << link->data << endl;
if (link != link->pNext)
traverse(link->pNext);
}
void reverseTraverse(Node *link){
if (link != link->pNext)
traverse(link->pNext);
cout << link->data << endl;
}
};
int main(){
cout << " Hello Worldn";
List list;
for (int i = 0; i <= 9; ++i)
list.insert(i);
list.remove(5);
cout << "removed 5n";
cout << "traverse" << endl;
list.traverse();
cout << "reverse" << endl;
list.reverseTraverse();
system("PAUSE");
return 0;
}
您的问题是,如果您说:
Node temp(data);
那么它只是一个局部变量,它将在封闭函数(例如insert函数)结束后消失。请改用new,然后在删除时将其删除。
顺便说一句,你不需要List类。节点就是列表。