反向输出链表
来自经典100例
1 #include<stdio.h>
2 #include<stdlib.h>
3
4 struct link
5 {
6 int data;
7 struct link *next;
8 };
9
10 //node is a type,link is a node point type
11 typedef struct link node;
12 typedef node *link;
13
14 //List delete free memory
15 void List_delete(link head,link tail)
16 {
17 link for_del;
18 for_del = head;
19
20 while(for_del!=tail)
21 {
22 head = head->next;
23 free(for_del);
24 for_del=head;
25 }
26 free(for_del);
27 }
28
29 //Traverse all data
30 void ListTraverse(link head)
31 {
32 link ptr;
33 ptr=head->next;
34
35 while(ptr!=NULL)
36 {
37 printf("%d ",ptr->data);
38 ptr=ptr->next;
39 }
40 printf("\n");
41 }
42
43 int main()
44 {
45 link ptr,head,tail;
46 int temp,i;
47
48 tail = (link)malloc(sizeof(node));
49 ptr = tail;
50
51 //new a link
52 printf("please input 5 int data:");
53 for(i=0;i<5;i++)
54 {
55 scanf("%d",&temp);
56 ptr->data=temp;
57
58 //下面这句会不会出现重复分配内存的现象。不会,计算机分配了一块,ptr用了之后,再在别一个地方分配别一块
59 head = (link)malloc(sizeof(node));
60 head->next=ptr;
61 ptr = head;
62 }
63
64 //traverse
65 ListTraverse(head);
66
67 //delete the link free memory
68 List_delete(head,tail);
69
70 return 0;
71 }
2 #include<stdlib.h>
3
4 struct link
5 {
6 int data;
7 struct link *next;
8 };
9
10 //node is a type,link is a node point type
11 typedef struct link node;
12 typedef node *link;
13
14 //List delete free memory
15 void List_delete(link head,link tail)
16 {
17 link for_del;
18 for_del = head;
19
20 while(for_del!=tail)
21 {
22 head = head->next;
23 free(for_del);
24 for_del=head;
25 }
26 free(for_del);
27 }
28
29 //Traverse all data
30 void ListTraverse(link head)
31 {
32 link ptr;
33 ptr=head->next;
34
35 while(ptr!=NULL)
36 {
37 printf("%d ",ptr->data);
38 ptr=ptr->next;
39 }
40 printf("\n");
41 }
42
43 int main()
44 {
45 link ptr,head,tail;
46 int temp,i;
47
48 tail = (link)malloc(sizeof(node));
49 ptr = tail;
50
51 //new a link
52 printf("please input 5 int data:");
53 for(i=0;i<5;i++)
54 {
55 scanf("%d",&temp);
56 ptr->data=temp;
57
58 //下面这句会不会出现重复分配内存的现象。不会,计算机分配了一块,ptr用了之后,再在别一个地方分配别一块
59 head = (link)malloc(sizeof(node));
60 head->next=ptr;
61 ptr = head;
62 }
63
64 //traverse
65 ListTraverse(head);
66
67 //delete the link free memory
68 List_delete(head,tail);
69
70 return 0;
71 }

浙公网安备 33010602011771号