我正在尝试找出以下代码来为链接列表实现push_back
函数,但我不确定为什么我们需要back_ptr->next
和back_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;
};
答案 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