链表回推操作中需要'back pointer'

Need for 'back pointer' in linked List push back operation

本文关键字:back pointer 操作 链表      更新时间:2023-10-16

我正在尝试找出以下代码来实现链表的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;
};
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
└────┴────┘   └────┴────┘   └────┴────┘

让我解释一下,如果在回推时列表不为空,当前尾部的节点应将其指向新节点旁边,最后尾部应指向新节点。

     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