写的一个链表
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 #define TRUE 1; 5 #define FALSE 0; 6 7 typedef struct Node 8 { 9 int value; 10 struct Node *next; 11 }ST_Node; 12 13 14 extern ST_Node *creat_Linked_List(int Lenth); 15 extern int insert_Node(ST_Node *current,int new_value); 16 extern int print_list(ST_Node *current,ST_Node *New_Node); 17 18 19 20 /*上面只是定义了一个结构体类型,并未实际分配内存空间 21 22 只有定义了变量才分配内存空间*/
1 #include "common.h" 2 3 int main() 4 5 { 6 7 int Lenth; 8 int insert_value; 9 ST_Node *New_Node; 10 ST_Node *root; 11 12 printf(" please input the lenth of the linked list: "); 13 14 scanf("%d",&Lenth); 15 16 New_Node = creat_Linked_List(Lenth);/*链表的头指针(head)来标记整个链表*/ 17 18 root = New_Node; 19 printf(" output the value of the node: "); 20 21 print_list(root,New_Node); 22 23 printf(" input the number you want insert: "); 24 25 scanf("%d",&insert_value); 26 insert_Node(root , insert_value); 27 28 printf(" output the value of the node: "); 29 root = New_Node; 30 print_list(root,New_Node); 31 32 33 return 0; 34 }
1 #include "common.h" 2 3 /*create a list and the size is chageble*/ 4 ST_Node *creat_Linked_List(int Lenth) 5 6 { 7 8 int i; 9 10 ST_Node *head,*New_Node,*Node; 11 12 /*head用来标记链表,New Node总是用来指向新分配的内存空间,Node总是指向尾结点,并通过Node来链入新分配的结点*/ 13 14 int a; 15 16 head=NULL; 17 18 for(i=1;i<=Lenth;i++) 19 20 { 21 22 New_Node=(ST_Node *)malloc(sizeof(ST_Node)); 23 if(NULL == New_Node) 24 { 25 return FALSE; 26 printf("内存分配失败"); //内存分配失败 返回0; 27 } 28 29 /*动态分配内存空间,并数据转换为(struct Node)类型*/ 30 printf(" please input the value of NO.%d:",i); 31 scanf("%d",&a); 32 New_Node->value = a; 33 if(NULL == head)/*指定链表的头指针*/ 34 { 35 head = New_Node; 36 Node = New_Node; 37 } 38 else 39 { 40 Node->next = New_Node; 41 Node = New_Node; 42 } 43 Node->next = NULL; /*尾结点的后继指针为NULL(空)*/ 44 } 45 return head;/*返回链表的头指针*/ 46 47 } 48 49 50 /*insert a node into the list*/ 51 int insert_Node(ST_Node *current,int new_value) 52 { 53 ST_Node *previous; 54 ST_Node *new; 55 while((current->value) < new_value) 56 { 57 previous = current; 58 current = current ->next; 59 } 60 61 new = (ST_Node*) malloc(sizeof(ST_Node)); 62 63 new->value = new_value; 64 65 new->next = current; 66 previous->next = new; 67 68 return TRUE; 69 } 70 71 int print_list(ST_Node *current,ST_Node *New_Node) 72 { 73 74 New_Node = current; 75 while(New_Node)/*直到结点New_Node为NULL结束循环*/ 76 77 { 78 79 printf("%d ",New_Node->value);/*输出结点中的值*/ 80 81 New_Node = New_Node->next;/*指向下一个结点*/ 82 83 } 84 printf(" "); 85 return TRUE; 86 }