我目前正在學習如何使用鏈接列表,特別是雙向鏈接列表,並且當我嘗試向後打印時遇到了與我的程序有關的問題。打印雙向鏈接列表
下面是代碼的,我需要幫助的部分:
#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