单链表头插法的实现
1 #include <stdio.h> 2 #include <string.h> 3 #include <stdlib.h> 4 #include <ctype.h> 5 6 typedef struct node{ 7 char data[10]; 8 struct node*next; 9 }ListNode; 10 11 typedef ListNode *LinkList; 12 LinkList CreatListR1(); 13 LinkList CreatList(); 14 ListNode *LocateNode(LinkList head,char *key); 15 void DeleteList(); 16 void printlist(LinkList head); 17 void DeleteAll(LinkList head); 18 ListNode *AddNode(LinkList head); 19 20 int main(){ 21 char ch[10],num[5]; 22 LinkList head; 23 head=CreatList(); 24 printlist(head); 25 printf("Delete Node(y/n):"); 26 scanf("%s",num); 27 if(strcmp(num,"y")==0||strcmp(num,"Y")==0){ 28 head=AddNode(head); 29 } 30 printlist(head); 31 system("pause"); 32 DeleteAll(head); 33 } 34 35 36 LinkList CreatListR1(){ 37 char ch[10]; 38 LinkList head=(LinkList)malloc(sizeof(ListNode)); 39 ListNode*s,*r,*pp; 40 r=head; 41 r->next==NULL; 42 printf("Input # to end"); 43 printf("\nPlease input Node_data "); 44 scanf("%s",ch); 45 while(strcmp(ch,"#")!=0){ 46 pp=LocateNode(head,ch); 47 48 if(pp==NULL){ 49 s=(ListNode *)malloc(sizeof(ListNode)); 50 strcpy(s->data,ch); 51 r->next=s; 52 r=s; 53 r->next=NULL; 54 } 55 printf("Input # to end "); 56 printf("Please input Node_data:"); 57 scanf("%s",ch); 58 } 59 return head; 60 } 61 62 63 64 LinkList CreatList(){ 65 char ch[100]; 66 LinkList head,p; 67 head=(LinkList)malloc(sizeof(ListNode)); 68 head->next=NULL; 69 while(1){ 70 printf("Input # to end "); 71 printf("Please input Node_data:"); 72 scanf("%s",ch); 73 if(strcmp(ch,"#")){ 74 if(LocateNode(head,ch)==NULL){ 75 strcpy(head->data,ch); 76 p=(LinkList)malloc(sizeof(ListNode)); 77 p->next=head; 78 head=p; 79 } 80 } 81 else 82 break; 83 } 84 return head; 85 } 86 87 ListNode *LocateNode(LinkList head,char *key){ 88 ListNode *p=head->next; 89 while(p!=NULL&&strcmp(p->data,key)!=0){ 90 p=p->next; 91 } 92 return p; 93 } 94 95 ListNode *AddNode(LinkList head){ 96 char ch[10]; 97 ListNode *s,*pp; 98 printf("\nPlease input a New Node_data:"); 99 scanf("%s",ch); 100 pp=LocateNode(head,ch); 101 if(pp==NULL){ 102 s=(ListNode *)malloc(sizeof(ListNode)); 103 strcpy(s->data,ch); 104 s->next=head->next; 105 head->next=s; 106 } 107 return head; 108 } 109 110 void DeleteList(LinkList head,char *key){ 111 ListNode *p,*r,*q=head; 112 p=LocateNode(head,key); 113 if(p==NULL){ 114 printf("position error"); 115 exit(0); 116 } 117 while(q->next!=p) 118 q=q->next; 119 r=q->next; 120 q->next=r->next; 121 free(r); 122 } 123 124 void printlist(LinkList head){ 125 ListNode *p=head->next; 126 while(p){ 127 p=p->next; 128 } 129 printf("\n"); 130 } 131 void DeleteAll(LinkList head){ 132 ListNode *p=head,*r; 133 while(p->next){ 134 r=p->next; 135 free(p); 136 p=r; 137 } 138 free(p); 139 }
有些飘,时间安排的也不是很合理,稀里糊涂的度日子。从基础开始,从现在开始,加油吧,少年郎。