头插法逆置单向链表
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 typedef struct node{ 5 int item; 6 struct node *next; 7 }node; 8 9 void list_show(node *); 10 11 //创建一个长度为10的链表 12 node *creat_node_list() 13 { 14 node *h,*p,*l; 15 int n = 10; 16 h = (node *)malloc(sizeof(node)); 17 h->item = 10; 18 h->next = NULL; 19 20 p = h; 21 22 while(--n){ 23 l = (node *)malloc(sizeof(node)); 24 l->item = n; 25 l->next = NULL; 26 p->next = l; 27 p = l; 28 } 29 return h; 30 } 31 32 //逆置链表,头插法 33 node *tran_list(node *h) 34 { 35 node *p,*l; 36 p = NULL; 37 l = NULL; 38 39 while(h != NULL){ 40 p = h->next; 41 h->next = l; 42 l = h; 43 h = p; 44 } 45 return l; 46 } 47 48 void list_show(node *p) 49 { 50 while(p != NULL){ 51 printf("%d ",p->item); 52 p = p->next; 53 } 54 printf(" "); 55 } 56 57 int main(void) 58 { 59 node *h; 60 h = creat_node_list(); 61 list_show(h); 62 h = tran_list(h); 63 list_show(h); 64 return 0; 65 }
运行结果: