我正在尝试编写一个反向打印函数作为双向链表的一部分。以下是我编写的相关函数:
void PLAYER::AddNode(int addID, std::string addName){
nodePtr n = new node; //creates a new node pointer
n->next = NULL; //Make next null
n->prev = NULL; // this will set this to be the ending node
n->ID = addID; //These two lines pass the information into the node
n->name = addName; // ID# and Name Information
if(head != NULL){ // This checks to see if a list is set up.
curr = head; // Make this point to the head.
while(curr->next != NULL){ // Loops through until the NULL is found
curr = curr->next;
}
curr->next = n; //Make the currnet node point to N
n->prev = curr; //Make the previous node connect to curr
n->next = tail; // connect new node to the tail.
}
else{
head = n; //If there is no list, this makes N the first node.
}
这是对要使用的函数进行原型(prototype)设计的类。
class PLAYER
{
public: // Functions go inside PUBLIC
PLAYER();
void AddNode(int addID, std::string addName);
void DeleteNode(int delPlayer);
void SortNode();
void PrintList();
void InsertHead(int AddID, std::string addName);
void PrintReverse();
private: //Variables go into here
typedef struct node{
// ...
std::string name;
int ID;
node* next;
node* prev;
}* nodePtr;
nodePtr head, curr, temp, prev, test, tail;
};
最后我尝试创建一个反向遍历函数来向后打印。
void PLAYER::PrintReverse()
{
curr = head;
while(curr->next != NULL) //Get to the end of the list
{
curr = curr->next;
}
while(curr->prev != NULL) //Work backward and print out the contents
{
std::cout << curr->ID << " " << curr->name << endl;
curr = curr->prev;
}
}
我想做的是在 PrintReverse() 函数中让它通过尾指针初始化,但是我无法弄清楚要添加到 PrintReverse() 和 AddNode() 的函数以获得新节点尾部指向。
这是我在这里发布的第一个问题,我希望我涵盖了我的所有基础。感谢您提供我能找到的任何帮助。
编辑:
感谢您的所有意见。我正在重新学习数据结构,是的,这是我自己做的一些功课,目的是让逻辑重新开始流动。
我今晚回家后会进行更改。
最佳答案
需要考虑以下更改。
PrintReverse
函数不需要正向传递来获取tail
。
void PLAYER::PrintReverse()
{
curr = tail;
while(curr != NULL) //Work backward and print out the contents
{
std::cout << curr->ID << " " << curr->name << endl;
curr = curr->prev;
}
}
AddNode
函数中尾部的处理方式存在问题。查看注释包含 [CHANGED]
和 [ADDED]
的行:
if(head != NULL){ // This checks to see if a list is set up.
curr = head; // Make this point to the head.
while(curr->next != NULL){ // Loops through until the NULL is found
curr = curr->next;
}
curr->next = n; //Make the currnet node point to N
n->prev = curr; //Make the previous node connect to curr
n->next = NULL; // [CHANGED]: we want the last node not to have a successor.
}
else{
head = n; //If there is no list, this makes N the first node.
}
tail = n; // [ADDED]: the last node added is the new tail.
然而,更简单的解决方案是再次避免前向传递,并从尾部开始。
if(tail != NULL){ // This checks to see if a list is set up.
tail->next = n; //Make the old tail node point to N
n->prev = tail;
n->next = NULL;
}
else{
head = n; //If there is no list, this makes N the first node.
}
tail = n; // The last node added is the new tail.
关于C++双链表反向打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36755311/