Reputation: 135
My assignment is to create a list in our main function and then display those numbers as a list. Then, we are supposed to show that it also traverses by displaying for example a reverse of that list. My problem is that I cannot seem to get the traversing part to display.Basically, anything that does not have a comment line after, the professor had already provided. Anything that has a comment line, I added. Thanks
#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(); //
}
Upvotes: 1
Views: 1277
Reputation: 43662
The problem with your code is in the node insertion routine:
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
}
change it to:
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;
}
and tail
needs to be initialized too:
tail = p->insert_after(40);
Upvotes: 2