反转单向链表

  据说在求职面试中,经常会出反转链表难题,意思就是将 a->b->c->d->e 这样单向链表转成 e->d->c->b->a 。仔细想来这也不是非常难以解决的问题!常见的两种思路是:1.设置一个辅助指针(auxiliary pointer);2.利用递归(recursion)。在经历了无数打击之后,还是觉得先从算法,从编码开始,从而提高自己编码水平!下面是我对两种思路的程序实现,写在此,仅以此为起点,踏上程序实践的路途。

 1 /*
 2 *    reverse single direct linklist
 3 */
 4 #include <stdio.h>
 5 #include <stdlib.h>
 6 
 7 typedef int KeyType;
 8 typedef struct LNode{
 9     KeyType data;
10     struct LNode *next;
11 }*LN;
12 
13 void initList(LN &L){
14     LN tmpPtr;
15     L = (struct LNode *)malloc(sizeof(LN));
16     L->next = NULL;
17     tmpPtr = L;
18     KeyType key;
19     printf("input elem:");
20     while(scanf("%d",&key)){
21         if(key==-1) return;
22         LN tmpPtr1 = (struct LNode*)malloc(sizeof(LN));
23         if(!tmpPtr){
24             printf("malloc error!\n");
25             return;
26         }
27         tmpPtr1->data = key;
28         tmpPtr1->next = NULL;
29         tmpPtr->next = tmpPtr1;
30         tmpPtr = tmpPtr1;
31         printf("input elem:");
32     }
33 }
34 
35 /* reverse function, use a auxiliary pointer */ 
36 void reverseList(LN &L){
37     if(!L->next)
38         return ;
39     LN pre;
40     LN cur;
41     LN next;
42     
43     pre = L->next;
44     cur = pre->next;
45     
46     while(cur){
47         next = cur->next;
48         cur->next = pre;
49         pre = cur;
50         cur = next;
51     }
52     L->next->next = NULL;
53     L->next = pre;
54 }
55 
56 /*
57 * use recursion
58 */
59 LN reverseListRecursion(LN p, LN& L){
60     if(p==NULL || p->next==NULL){
61         L->next = p ;
62         return p;
63     }else{
64         LN tmp = reverseListRecursion(p->next, L);
65         tmp->next = p ;
66         p->next = NULL; 
67         return p;
68     }
69 }
70 
71 void printList(LN &L){
72     LN ptr=L->next;
73     while(ptr){
74         printf(" %d ",ptr->data);
75         ptr = ptr->next;
76     }
77     printf("\n");
78 }
79 
80 int main(int argc, char **argv){
81     LN L;
82     initList(L);
83     printList(L);
84     //reverseListRecursion(L);
85     reverseListRecursion(L->next, L);
86     printList(L);
87     return 0;
88 }
原文地址:https://www.cnblogs.com/HackingProgramer/p/2718615.html