標籤:style color 使用 os strong io for 2014
-
題目描述:
-
輸入一個鏈表,反轉鏈表後,輸出鏈表的所有元素。
(hint : 請務必使用鏈表)
-
輸入:
-
輸入可能包含多個測試範例,輸入以EOF結束。
對於每個測試案例,輸入的第一行為一個整數n(0<=n<=1000):代表將要輸入的鏈表的個數。
輸入的第二行包含n個整數t(0<=t<=1000000):代錶鏈表元素。
-
輸出:
-
對應每個測試案例,
以此輸出鏈表反轉後的元素,如沒有元素則輸出NULL。
-
範例輸入:
-
51 2 3 4 50
-
範例輸出:
-
5 4 3 2 1NULL
代碼:
有遞迴和非遞迴兩種方案.
/*反轉鏈表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(Node));scanf("%d",&data);;if(!pNew){exit(-1);}pNew->data = data;pNew->next = NULL;pTemp->next = pNew;pTemp = pNew;}}//反轉鏈表,返回反轉鏈表的頭結點//非遞迴List reverseList(List 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;}//遞迴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(NULL,pHead);}int main(){int n;while(scanf("%d",&n) != EOF){List 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;}