In this code,
if I input 3 as the item created
the result is
"
[0]->[1]->[2]->Null
[0]->Head
"
but i expect the result should be
"
[0]->[1]->[2]->Null
[2]->[1]->[0]->Head
"
how can i modify the code in the member function
"void Print_Doubly_linked_list_reversely(Doubly_linked_list *ptr)"
in order to have the result
"[2]->[1]->[0]->Head"
void Print_Doubly_linked_list_reversely(Doubly_linked_list *ptr)
{
//what can i do here?
while(ptr!=0)
{
cout<<"["<<ptr->GetNum()<<"]->";
ptr=ptr->GetPrev();
}
cout<<"Head"<<endl;
cout<<endl;
}
1 2 3 4 5 6 7 8 9 10 11 12
int main()
{
int num;
Doubly_linked_list *headPtr;
Doubly_linked_list *newPtr;
cout<<"How many items you want to create? ";
cin>>num;
headPtr= Create_Doubly_linked_list(num);
Print_Doubly_linked_list(headPtr);
Print_Doubly_linked_list_reversely(headPtr);
return 0;
}
To print the list in reverse you will need to start at the last pointer (call it tailPtr), not at headPtr.
The tailPtr is the last value taken by tempPtr in your Create_Doubly_linked_list() function.
Maybe you could add a 2nd argument to the function, something like: Create_Doubly_linked_list(int n, Doubly_linked_list *& tailPtr) then assign tailPtr = tempPtr; when the do loop ends in the function. Note: A reference to a pointer is needed for the 2nd argument (or a pointer to the pointer-take your pick).
Assuming you go with the Doubly_linked_list*& as an argument, in main():
1 2 3 4 5 6 7 8 9 10 11 12
int main()
{
int num;
Doubly_linked_list *headPtr;
Doubly_linked_list *tailPtr;// you didn't need newPtr anyways
cout<<"How many items you want to create? ";
cin>>num;
headPtr= Create_Doubly_linked_list(num, tailPtr);// value for tailPtr is recorded
Print_Doubly_linked_list(headPtr);
Print_Doubly_linked_list_reversely(tailPtr);// start at the tail, not the head.
return 0;
}