链表回推操作中需要'back pointer'
Need for 'back pointer' in linked List push back operation
我正在尝试找出以下代码来实现链表的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;
};
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
相关文章:
- C++ - "!pointer"和"pointer == nullptr"的区别?
- 推导 std::vector::back() 的返回类型
- vector.back() 和 vector[vector.size() - 1] 之间的区别?
- "No-Const Pointer to Const "调用功能
- "owned pointer"和 std::shared_ptr 的"stored pointer"有什么区别?
- 删除分配的 (?) 指针时"Pointer being freed was not allocated"
- vector.push_back(vector.back()+1) 是未定义的行为吗?
- C++ 中的构造函数、继承、堆栈、堆、this-pointer 和段错误
- "Called Object Type is Not a Function or Pointer" 与 typedef 和类
- 马洛克会在 C++17 年返回"invalid pointer value"吗?
- c++为什么decltype(*pointer)会产生引用
- 指向对象生存期之外的已分配内存的指针是"invalid pointer[s]"还是"pointer[s] to an object"?
- 为什么"non-standard syntax; use '&' to create a pointer to member"在 CTOR 中使用线程?
- Golang CGO with large char pointer语言 - SEGSERV
- 向量<pointer>:插入(迭代器,指针)插入垃圾值
- 线路抑制状态错误 C4703 可能未初始化的局部指针变量"back"已使用
- std::vector using back(), pop_back(), push_back(), 得到'double free or corruption'错误
- 在 C++ 中,这两种"pointer delete"操作有什么区别?
- vector.back()和vector.end()有什么区别
- 链表回推操作中需要'back pointer'