-
Description:
-
Enter a linked list. After the linked list is reversed, all elements of the linked list are output.
(Hint: please be sure to use the Linked List)
-
Input:
-
The input may contain multiple test examples. The input ends with EOF.
For each test case, the first input behavior is an integer N (0 <= n <= 1000): represents the number of linked lists to be input.
The second line of the input contains N integers t (0 <= T <= 1000000): representing the linked list element.
-
Output:
-
Corresponding to each test case,
Output the elements after the chain table is reversed. If no element exists, null is output.
-
Sample input:
-
51 2 3 4 50
-
Sample output:
-
5 4 3 2 1NULL
Code:
There are recursive and non-recursive solutions.
/* Reverse linked list by rowandjj2014/7/31 */# include <stdio. h> # include <stdlib. h> typedef struct _ node _ {int data; struct _ node _ * Next;} node, * pnode, * List; void create (list * List, int N) {If (n <= 0) {return;} int data; scanf ("% d", & data); * List = (pnode) malloc (sizeof (node )); if (* List = NULL) {exit (-1) ;}( * List)-> DATA = data; (* List)-> next = NULL; pnode ptemp = * List; For (INT I = 0; I <n-1; I ++) {pnode pnew = (pnode) malloc (sizeof (nod E); scanf ("% d", & data); If (! Pnew) {exit (-1) ;}pnew-> DATA = data; pnew-> next = NULL; ptemp-> next = pnew; ptemp = pnew ;}} // returns the head node of the reverse linked list. // non-recursive list reverselist (list) {pnode phead = NULL, pcur = List, PPRE = NULL; while (pcur! = NULL) {pnode pnext = pcur-> next; If (pnext = NULL) {phead = pcur;} pcur-> next = PPRE; PPRE = pcur; pcur = pnext;} return phead;} // recursive list reverselist_2 (pnode PPRE, pnode pcur) {If (pcur = NULL) {return NULL ;} if (pcur-> next = NULL) {pcur-> next = PPRE; return pcur;} pnode pnext = pcur-> next; pcur-> next = PPRE; pnode phead = reverselist_2 (pcur, pnext); Return phead;} pnode reverse (pnode phead) {return reverselist_2 (NUL L, phead);} int main () {int N; while (scanf ("% d", & N )! = EOF) {list = NULL; Create (& list, n); List = reverse (list); If (list = NULL) {printf ("null \ n");} pnode Pt = List; while (PT! = NULL) {If (Pt-> next = NULL) printf ("% d \ n", Pt-> data); else printf ("% d ", pt-> data); Pt = Pt-> next;} return 0 ;}