標籤:style blog http color io os 使用 ar for
轉載請註明出處:http://blog.csdn.net/ns_code/article/details/25737023
本文分別用非遞迴和遞迴兩種方式實現了鏈表的反轉,在九度OJ上AC。
-
題目描寫敘述:
-
輸入一個鏈表,反轉鏈表後,輸出鏈表的全部元素。
(hint : 請務必使用鏈表)
-
輸入:
-
輸入可能包括多個測試例子,輸入以EOF結束。
對於每一個測試案例,輸入的第一行為一個整數n(0<=n<=1000):代表將要輸入的鏈表的個數。
輸入的第二行包括n個整數t(0<=t<=1000000):代錶鏈表元素。
-
輸出:
-
相應每一個測試案例,
以此輸出鏈表反轉後的元素,如沒有元素則輸出NULL。
-
例子輸入:
-
51 2 3 4 50
-
例子輸出:
-
5 4 3 2 1NULL
非常明顯,翻轉後,尾節點和頭結點互換了。
我們須要設定三個指標,分別指向當前要反轉的節點、當前要反轉節點的前一個節點、當前要反轉節點的下一個節點。要注意鏈表為空白,以及僅僅有一個頭結點的情況。
非遞迴實現例如以下:
/*反轉鏈表,返回翻轉後的頭結點*/pNode ReverseList(pNode pHead){if(pHead == NULL)return NULL;if(pHead->next == NULL)return pHead;pNode pCur = pHead;pNode pPre = NULL;while(pCur != NULL){pNode pNext = pCur->next;pCur->next = pPre;pPre = pCur;pCur = pNext;}return pPre;} 遞迴實現例如以下:
/*遞迴實現反轉鏈表,返回翻轉後的頭結點*/pNode ReverseListRecursivly(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 pNewHead = ReverseListRecursivly(pCur,pNext);return pNewHead;}pNode ReverseList2(pNode pHead){return ReverseListRecursivly(NULL,pHead);}
依據題目要求,測試代碼例如以下:
int main(){int n;while(scanf("%d",&n) != EOF){pNode pHead = NULL;if(n > 0){int i,data;scanf("%d",&data);pHead =(pNode)malloc(sizeof(Node));if(pHead == NULL)exit(EXIT_FAILURE);pHead->data = data;pHead->next = NULL;pNode pCur = pHead;for(i=0;i<n-1;i++){scanf("%d",&data);pNode pNew =(pNode)malloc(sizeof(Node));if(pNew == NULL)exit(EXIT_FAILURE);pNew->data = data;pNew->next = NULL;pCur->next = pNew;pCur = pCur->next;}}pNode pNewHead = ReverseList2(pHead);if(pNewHead == NULL)printf("NULL\n");else{pNode pCur = pNewHead;while(pCur != NULL){//這裡主要時要注意輸出的格式if(pCur->next == NULL)printf("%d\n",pCur->data);elseprintf("%d ",pCur->data);pCur = pCur->next;}}}return 0;}
/************************************************************** Problem: 1518 User: mmc_maodun Language: C Result: Accepted Time:150 ms Memory:2364 kb****************************************************************/
【劍指offer】遞迴迴圈兩種方式反轉鏈表