我目前正在学习如何使用链接列表,特别是双向链接列表,并且当我尝试向后打印时遇到了与我的程序有关的问题。打印双向链接列表
下面是代码的,我需要帮助的部分:
#include <iostream>
using namespace std;
struct node
{
int data; //int to store data in the list
node *next; //pointer to next value in list
node *prev; //pointer to previous value in list
};
node *appendList(node *current, int newData) //Function to create new nodes in the list
{
node *newNode; //create a new node
newNode = new node;
newNode->data = newData; //Assign data to it
newNode->next = NULL; //At end of list so it points to NULL
newNode->prev = current; //Link new node to the previous value
current->next = newNode; //Link current to the new node
return newNode; //return the new node
}
node *createList(int maxLoop, node *begin, node *current, node *end) //Function to create list
{
//Allocate the starting node
current = new node;
current -> data = 1; //First data value is 1
current -> next = NULL; //next value is NULL
current -> prev = NULL; //previous value is NULL
begin = current; //This is the beginning of the list
for (int count = 2; count <= maxLoop; count++) //Loop to fill the list
{
current = appendList(current, count*count); //Create new nodes and fill with square numbers
}
end = current; //Now we are at the end of the list
return begin; //Return begin, this is the problem; I can't return end as well
}
void printForward (node *p) //Function to print the list forwards
{
node *curr = p; //current is the beginning value of the list
while (curr != NULL) //Continue while current is not at the end of the list
{
cout << curr->data << " "; //Print out the data of current
curr = curr->next; //Move one value along in the list
}
}
void printBackward (node *p) //Function to print the list backwards
{
node *curr = p; //current is the end value of the list
while (curr != NULL) //Continue while current is not at the beginning of the list
{
cout << curr->data << " "; //Print out the data of current
curr = curr->prev; //Move one value back in the list
}
}
int main()
{
//Initialize current, begin, and end
node *current = NULL;
node *begin = NULL;
node *end = NULL;
int maxLoop = 10; //The number of items in the list
cout << "The list has now been created." << endl;
begin = createList(maxLoop, begin, current, end); //function to create the list
cout << "Printed forwards, this list is: ";
printForward(begin); //Function to print the list forwards
cout << endl;
cout << "Printed backwards, this list is: ";
printBackward(end); //Function to print the list backwards
cout << endl;
return 0;
}
该计划的目的是创建一个列表,转发打印,向后,插入一个元素,删除一个元素,然后销毁该清单。我已经将它简化为创建,向前打印和向后打印功能。
我遇到的问题是在createList函数中,我正在修改begin和end,但我只能返回一个或另一个。这意味着无论哪个我不返回在主函数中仍然是NULL,因此不指向任何东西。我试着将begin/current/end设置为不等于NULL,但如果我这样做,createList将不起作用。
有没有人有任何想法,我怎么可以修改两者?只需要清楚,在功能中创建的列表HAS TO,在主要初始化它将非常容易。
感谢, 特里斯坦
您可以参考指针(node *&begin) – Kevin