如何在C++的链表中创建上一个指针
How to create a previous pointer in a linked list in C++?
我创建了一个 LinkedList 类,该类具有删除列表中第一个元素的函数和删除列表中最后一个元素的函数。 第一个很简单,删除元素后,我将其设置为指向下一个元素。 效果很好。 但是,当我删除最后一个元素时,我必须将其指向列表中的前一个元素,该元素在该点成为最后一个元素。 我不知道该怎么做。 请指教。 这是代码:
void LinkedList::pop_front()
{
mFront->data = NULL;
mFront = mFront->next;
}
如何获得删除最后一个元素但重置尾部以指向新尾部的函数?
void LinkedList::pop_back()
{
mBack->data = NULL;
...
}
class LinkedList
{
public:
// Default Constructor
// Purpose: Initializes an empty list
// Parameters: none
// Returns: none
LinkedList();
// The push_front function
// Purpose: add an item to the front of the list
// Parameters: a int item for the front
// Returns: none
void push_front(int data);
// The push_back function
// Purpose: insert an item into the back of the list
// Parameters: int item to add the the back
// Returns: none
void push_back(int data);
// The pop_front function
// Purpose: delete the item in the front of the list
// Parameters: none
// Returns: none
void pop_front();
// the pop_back function
// Purpose: remove the item at the end of the list
// Parameters: none
// Returns: none
void pop_back();
// The getFirst function
// Purpose: print the first item in the list
// Parameters: none
// Returns: none
void getFirst();
// the GetLast function
// Purpose: return the last item in the list
// Parameters: none
// Returns: none
void getLast();
void printList();
// the clear function
// Purpose: clear the list, free memory
// Parameters: none
// Returns: none
void clear();
// Destructor
// Purpose: clear up memory
// Parameters: none
// Returns: none
~LinkedList();
private:
LinkedList *mFront; // point to the front of our list
LinkedList *mBack; // point to the back of our list
LinkedList *next; // the next node
LinkedList *previous; // the previous node
int data; // our list data manipulator
单向链表不提供最后一个元素的 O(1) 删除。您必须从一开始就浏览整个列表才能找到倒数第二个元素。
Node* i = mFront;
while ( i->next != mBack ) i = i->next;
mBack = i;
如果列表不是双链接的,则必须从第一个元素开始才能找到最后一个元素:
void LinkedList::pop_back()
{
mBack->data = NULL;
current = mFront;
do{
current = current->next
} while ( current->next );
mBack = current;
}
非常重要 - 由于data
似乎是一个指针,因此您可能会遇到内存泄漏。仅设置 data = NULL
不会释放内存,您必须显式删除它:
delete mFront->data;
相关文章:
- C++-我可以创建另一个类的成员并在构造函数中使用它吗
- 创建了一个链表,但如何删除 c++ 中的"所有"节点
- 从抽象类继承以创建另一个抽象类时,我应该重新声明所有虚函数吗?
- 如何检查第三个 API 是否在 Linux 中为 c/c++ 程序创建了一个新线程?
- 我在 C++ 中创建了一个函数来递归反转字符串,但是之后如何使功能打印一个 endl?
- 我已经创建了一个模板函数,但是在检查输入是奇数还是偶数时收到错误 C++.
- 将vector<vector<double>>从x86平台中创建的一个进程发送到x64中构建的另一个进程的最快方法是什么
- 我创建了一个库,想知道设计是否效率低下
- 类模板上一个特定函数的未解析外部符号
- 错误:"int pow(double,int)"与上一个声明int pov(double a,int
- 在课堂上创建了一个朋友,给出"无输入文件"错误
- 我创建了一个简单的程序,但有些地方不对劲
- 如何查看提升集中<cpp_int>的下一个和上一个元素
- 我想知道我将如何实现 + 运算符重载.我已经从我上一个问题中计算出 += 运算符重载
- Zmq 上下文 - 我应该在新线程中创建另一个上下文吗?
- 为什么MessageBox在我创建的桌面中显示窗口,而AllocConsole在上一个桌面中显示它
- 我将如何在 c++ 中创建一个实时更新覆盖上一个条目的循环
- 如何在C++的链表中创建上一个指针
- Ifstream停留在一个单词上,创建了一个无限循环
- 如何在Windows 7上运行可执行文件,这是由Qt Creator 5.0.2版本创建的一个发行版