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

时间:2014-10-05 19:28:49

标签: c++ c++11

我的任务是在主函数中创建一个列表,然后将这些数字显示为列表。然后,我们应该通过显示例如该列表的反向来表明它也遍历。我的问题是我似乎无法显示遍历的部分。基本上,任何没有评论后的内容,教授已经提供过。我补充说,任何有评论线的东西。谢谢

    #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(); //
       }

1 个答案:

答案 0 :(得分:2)

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

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