在链接List推回操作中需要'后退指针'

时间:2017-02-04 06:49:06

标签: c++ linked-list

我正在尝试找出以下代码来为链接列表实现push_back函数,但我不确定为什么我们需要back_ptr->nextback_ptr来指向p。我相信back_ptr->next可以指向NULL它的工作,是否有任何优势实现它,因为我失踪了?

void LinkedList::push_back(int element) {
    Node *p = new Node;
    p->element = elememt;
    p->next = 0;
    if (empty()) {
        front_ptr = back_ptr = p;
    } else {
        back_ptr->next = p;
        back_ptr = p;
    }
}

以下是LinkedList类原型。 back_ptr用于指向实现复制构造函数的列表末尾(push_back使复制列表变得容易得多。)

class LinkedList {
    void push_back(int element);
    // other member functions

    private:
    struct Node {
        Node *next;
        int element;
    };
    Node *front_ptr;
    Node *back_ptr;
};

2 个答案:

答案 0 :(得分:1)

push_back(1);
push_back(2);
Node *p = new Node;
p->element = 3;
p->next = nullptr;
 front_ptr      back_ptr         p
     ↓             ↓             ↓
┌────┬────┐   ┌────┬────┐   ┌────┬────┐
| #1 |next| → | #2 |next|   | #3 |next| → nullptr
└────┴────┘   └────┴────┘↘  └────┴────┘
                          nullptr
back_ptr->next = p;
 front_ptr      back_ptr         p
     ↓             ↓             ↓
┌────┬────┐   ┌────┬────┐   ┌────┬────┐
| #1 |next| → | #2 |next| → | #3 |next| → nullptr
└────┴────┘   └────┴────┘   └────┴────┘
back_ptr = p;
 front_ptr             back_ptr  p
     ↓                         ↘ ↓
┌────┬────┐   ┌────┬────┐   ┌────┬────┐
| #1 |next| → | #2 |next| → | #3 |next| → nullptr
└────┴────┘   └────┴────┘   └────┴────┘

答案 1 :(得分:0)

让我解释一下,在推回时列表是否为空,当前tail的节点应指向新节点旁边,最后tail应该指向新节点。

     Before push back 
     tail-> node x // tail points to node x
        x->next = null // as it is tail
     After push back new node y
       tail->next = y 
     As x was earlier pointed by tail ,this means x->next = p,

此步骤可确保列表保持连接状态。

     Finally , point the tail to the new node  
     tail -> y