Topic 1511: Printing a linked list from the end of the head
time limit:1 seconds
Memory limit:128 MB
Special question: No
submitted:6010
Resolution:1805
-
Title Description:
-
Enter a list to print the values of each node of the list from the end of the head.
-
Input:
-
Each input file contains only one set of sample test specimens.
Each set of test cases contains multiple lines, one integer greater than 0, representing the node of a linked list. The first line is the value of the first node in the list, and so on. When input to 1 indicates that the linked list is completed. -1 itself does not belong to the linked list.
-
Output:
-
Corresponds to each test case to output the value of each node of the list from the end of the tail, one row per value.
-
Sample input:
-
12345-1
-
Sample output:
-
54321
Reference code:
Recursive procedure.
1#include <iostream>2#include <stdio.h>3#include <stdlib.h>4#include <stack>5 using namespacestd;6typedefstructnode{7 intVal;8Node *Next;9 }node;Ten voidPrint_link (ConstNode *Tmp_node) { One if(tmp_node->next!=NULL) APrint_link (tmp_node->next); -printf"%d\n",tmp_node->val); - } the intMain () - { - //freopen ("D:\\input.txt", "R", stdin); - inttmp; +Node *head=Newnode; -head->next=NULL; +Node *pre_node=head; A while(SCANF ("%d", &tmp) &&tmp>0){ atNode *tmp_node=Newnode; -Tmp_node->val=tmp; -tmp_node->next=NULL; - -pre_node->next=Tmp_node; -Pre_node=Tmp_node; in } -Print_link (head->next); to return 0; +}
Your own code:
1#include <iostream>2#include <stdio.h>3#include <stdlib.h>4#include <stack>5 using namespacestd;6 structnode{7 intv;8Node *Next;9 };Ten voidPrint (node *p) { One if(P->next) {//attention!! APrint (p->next); - } -cout<<p->v<<Endl; the } - intMain () - { - //freopen ("D:\\input.txt", "R", stdin); + intN; -Node *head=Newnode (); +head->next=NULL; ANode *p,*q=head; at while(SCANF ("%d", &n) &&n!=-1){ -p=Newnode (); -p->v=N; -p->next=NULL; -q->next=p; -q=p; in } -Print (head->next); to return 0; +}
Nine degrees OJ topic 1511: Print linked list from tail to head