反轉鏈表

來源:互聯網
上載者:User

標籤: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;}





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.