Reprinted please indicate the source: http://blog.csdn.net/ns_code/article/details/25737023
In this article, we use non-recursive and recursive methods to reverse the linked list, and use the AC on the 9-degree OJ.
-
Description:
-
enter a linked list. After the chain table is reversed, output all elements of the linked list.
(Hint: please use the linked list)
-
input:
-
the input may include multiple example samples, the input ends with EOF.
for each trial case, the first input behavior is an integer N (0 <= n <= 1000), which indicates 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 example,
Output the elements after the chain table is reversed. If no element exists, null is output.
-
Example input:
-
51 2 3 4 50
-
Example output:
-
5 4 3 2 1 null
Obviously, after the flip, the tail node and the header node are switched.
We need to set three pointers pointing to the current node to be reversed, the previous node to be reversed, and the next node to be reversed. Note that the linked list is empty and there is only one head node.
Non-recursive implementations are as follows:
/*反转链表,返回翻转后的头结点*/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;}Recursive Implementation is as follows:
/*递归实现反转链表,返回翻转后的头结点*/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);}
Based on the question requirements, the trial code is as follows:
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
****************************************************************/
[Offoffer] recursive loop two ways to reverse the linked list