현재 연결 목록, 특히 이중 연결 목록을 사용하는 방법을 배우고 있으며 역순으로 인쇄하려고하면 프로그램에 문제가 발생했습니다.이중 연결 목록 인쇄
#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이므로 아무 것도 가리 키지 않습니다. 시작/현재/끝을 NULL과 같지 않게 설정하려고 시도했지만 그렇게하면 createList가 작동하지 않습니다.
둘 모두 수정하는 방법에 대한 아이디어가 있습니까? 그냥 분명히하려면 목록 HAS TO이 함수에서 만들어지면 기본으로 초기화하는 것이 매우 쉽습니다.
감사합니다, 트리스탄
참조로 포인터를 가져올 수 있습니다 (노드 * 및 시작) – Kevin