gpt4 book ai didi

c++ - 如何显示链表(双向链表)的遍历?

转载 作者:行者123 更新时间:2023-11-30 04:00:37 24 4
gpt4 key购买 nike

我的任务是在 main 函数中创建一个列表,然后将这些数字显示为列表。然后,我们应该通过显示例如该列表的反向来显示它也遍历。我的问题是我似乎无法显示遍历部分。基本上,教授已经提供了后面没有注释行的任何内容。我添加了任何有注释行的内容。谢谢

    #include <iostream>

using namespace std;
struct Node {
int data;
Node* next;
Node* prev; //
Node(int d=0, Node* p=0, Node* n=0) : data(d), next(p), prev(n) {} //
Node* insert_after(int value);
Node* delete_();
void display_list_after() ;
void display_list_prev();
};

Node* Node::insert_after(int value) {
Node *p = new Node(value);
Node *n = p; //
p->next = next;
p->prev = this; //
next = p;
return p;
}
Node* Node::delete_(){ //
Node *p = this;
Node *n = 0;
if (prev != 0){ //
prev->next = next; //
n = prev; //
}

if (next != 0) { //
next = prev->prev; //

if (n == 0){ //
n = next; //
}
}
delete p;
return n; //
}
void Node::display_list_after() {
Node *head = this;
while(head != 0) {
cout << head->data << " ";
head = head->next;
}
cout << '\n';
}

void Node::display_list_prev() {
Node *tail = this; //
while(tail != 0) { //
cout << tail->data << " "; //
tail = tail->prev; //
}
cout<<'\n'; //

}
int main(){
Node *head= new Node(10);
Node *tail = head->insert_after(40);
Node *p = head->insert_after(20);
p = p->insert_after(25);
p = p->insert_after(30);
p = p->insert_after(35);
p->insert_after(40);
head->display_list_after();
tail->display_list_prev(); //
}

最佳答案

您的代码的问题在于节点插入例程:

Node* Node::insert_after(int value) {
Node *p = new Node(value);
Node *n = p; //
p->next = next; // this is right (usually NULL)
p->prev = prev; // this is wrong (this node is the previous of the next one)
next = p;
prev = n; // this is also wrong (previous is not the next one)
return p; // this is right since this is the next node
return n; // this is the same stuff and will never get executed
}

将其更改为:

Node* Node::insert_after(int value) {
Node *p = new Node(value);
Node *n = p; //
p->next = next;
p->prev = this; // this is the previous node for the next one
next = p;
return p;
}

tail也需要初始化:

tail = p->insert_after(40);

Try it out

关于c++ - 如何显示链表(双向链表)的遍历?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26206365/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com