Title: Enter the head node of a linked list, which in turn prints the value of each node from the end of the head.
1. Definition of structure, construction of linked list and output of linked list data
structlistnode{intdata; ListNode*next;};//using the tail interpolation method to construct the linked listListNode *init () {ListNode*head= (ListNode *)malloc(sizeof(ListNode)); Head->next=NULL; ListNode*last=Head; intdata; cout<<"Please enter: (Press-1 to end the list)"<<Endl; CIN>>data; while(data!=-1) {ListNode*temp= (ListNode *)malloc(sizeof(ListNode)); Temp->data=data; Temp->next=last->next;//the next of last is nulllast->next=temp; Last=temp; cout<<"Please enter: (Press-1 to end the list)"<<Endl; CIN>>data; } returnhead;}//Print linked listvoidPrint (ListNode *head) {ListNode*temp=head->Next; while(temp!=NULL) {cout<<" "<<temp->data; Temp=temp->Next; }}
2. Using the Stack implementation
//use stacks to print linked lists from tail to headvoidUsestack (ListNode *head) { if(head!=NULL) {Stack<int> s=stack<int>(); ListNode*temp=head->Next; while(Temp!=null)//loop into the stack{s.push (temp-data); Temp=temp->Next; } while(S.size ()! =0)//loop out the stack{cout<<" "<<S.top (); S.pop (); } }}
3. Reverse linked list (implemented with 3 pointers)
//Reverse the linked list to achieve inverse outputListNode *resert (ListNode *head) {ListNode*now=head->Next; ListNode*pre=NULL; ListNode*newhead=NULL; while(now!=NULL) {ListNode*next=now->next;//records the next node of the current node so that it reverses the pointer if(Next==null)//if the next node of the pointer to the current node is empty, the current node is logged and returned .Newhead=Now ; now->next=pre;//Invert Pointer//pointer moves backPre=Now ; now=Next; } ListNode*hhead= (ListNode *)malloc(sizeof(ListNode));//since the first number is empty, this adds a shorthhead->next=Newhead; returnHhead;}
Test code:
int Main () { *head=init (); Print (head); cout<<Endl; Usestack (head); cout<<Endl; Head=Resert (head); Print (head);}
Screen:
Print linked list from tail to head