1 //code by zzlpp && code for link_list training 2 typedef struct Node 3 { 4 int value; 5 struct Node *link; 6 }Node; 7 8 //头文件只包含节点的声明 文
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <malloc.h> 4 #include "node.h" 5 6 Node*creatnode(int value); 7 void insertnode( Node **pointer,int value ); 8 9 void main() 10 { 11 Node *p=creatnode(5); 12 Node **pointer=&p; 13 insertnode(pointer,3); 14 do 15 { 16 printf("%d\t",p->value); 17 p=p->link; 18 }while( p!=NULL ); 19 printf("\n"); 20 system("pause"); 21 } 22 Node *creatnode(int value) 23 { 24 Node *root; 25 root=( Node *)malloc( sizeof(Node) ); 26 if (root==NULL) 27 { 28 free( root ); 29 printf("error\n"); 30 exit(EXIT_FAILURE); 31 } 32 root->value=value; 33 root->link=NULL; 34 return root; 35 } 36 void insertnode( Node **pointer,int value ) 37 { 38 Node *current; 39 Node *previous; 40 41 previous=NULL; 42 current=*pointer; 43 44 Node *newnode=( Node* )malloc( sizeof(Node) ); 45 if ( newnode==NULL ) 46 { 47 free( newnode ); 48 printf("error\n"); 49 exit(EXIT_FAILURE); 50 } 51 newnode->value=value; 52 while ( current->value<value && current->link!=NULL ) 53 { 54 previous=current; 55 current=current->link; 56 } 57 if ( current->link==NULL ) 58 { 59 if ( current->value<value ) 60 { 61 current->link=newnode; 62 newnode->link=NULL; 63 } 64 else 65 { 66 newnode->link=current; 67 *pointer=newnode; 68 } 69 } 70 else 71 { 72 newnode->link=current; 73 previous->link=newnode; 74 } 75 }
和原书上写的有些出入,总的来说就是要考虑到3种情况,第一种是要考虑插在链表的中间,第二种是要考虑到查到结尾,最后是要你考虑到查到开头,这三种情况缺一不可,个人觉得如此处理更为清晰一些。
件名 “node.h”
时间: 2024-10-13 13:03:32