【劍指offer】遞迴迴圈兩種方式反轉鏈表

來源:互聯網
上載者:User

標籤: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】遞迴迴圈兩種方式反轉鏈表

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.