将链表转向,原来的链尾成为链头,链头成为链尾,结点间指针一律掉头,在屏幕显示
增加一个链表对象,然后将原来的链表从头开始读取,存入新的链表对象中,每一次的存取都要对原链表头的下一个结点进行一次保存,否则下次存取的时候会找不到原链表
1 #include
2 #include
3 #include
4
5 typedef struct list{
6 int id;
7 struct list next;
8 }LIST,*PLIST;
9
10 PLIST create_list()
11 {
12 PLIST p = NULL;
13 PLIST head = NULL;
14 int i = 0;
15 for(i=0;i 16 {
17 p = NULL;
18 p = malloc(sizeof(LIST));
19 memset(p,0,sizeof(LIST));
20 p->id = i;
21
22 p->next = head;
23 head = p;
24 }
25 return head;
26 }
27
28 PLIST inversion_list(PLIST *head)/頭插法反轉鏈表*/
29 {
30 printf("頭插法反轉鏈表\n");
31 PLIST p = NULL;
32 PLIST new_head = NULL;
33 while(*head != NULL)
34 {
35 p = head;
36 *head = (*head)->next;
37
38 p->next = new_head;
39 new_head = p;
40 }
41 return new_head;
42 }
43
44 PLIST inversion_list2(PLIST *head)/三個指針反轉鏈表*/
45 {
46 printf("三個指針反轉鏈表\n");
47 PLIST p_nex = NULL;
48 PLIST p_pre = NULL;
49 while((*head != NULL) && ((*head)->next != NULL))
50 {
51 p_nex = (*head)->next;
52
53 (*head)->next = p_pre;
54 p_pre = head;
55
56 *head = p_nex;
57 }
58 (*head)->next = p_pre;
59 return *head;
60 }
61
62 void show_list(PLIST head)
63 {
64 while(head != NULL)
65 {
66 printf("id:%d\n",head->id);
67 head = head -> next;
68 }
69 }
70
71 void release_list(PLIST *head)
72 {
73 printf("free 釋放空間\n");
74 PLIST p = NULL;
75 while(*head != NULL)
76 {
77 p = *head;
78 printf("free(%d)\n",p->id);
79 *head = (*head)->next;
80 free(p);
81 }
82 }
83
84 int main()
85 {
86 PLIST head = NULL;
87 head = create_list();/建立鏈表*/
88 if(head == NULL){
89 return 0;
90 }else {
91 printf("創建成功、\n");
92 }
93 show_list(head);/*遍歷鏈表*/
94
95 head = inversion_list(&head);/*反轉鏈表*/
96 show_list(head);/*遍歷鏈表*/
97
98 inversion_list2(&head);/*三個指針反轉鏈表*/
99 show_list(head);/*遍歷鏈表*/
100
101 release_list(&head);/*釋放鏈表*/
102 return 0;
103 }