双向链表的创建,查找,删除
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 /* 5 双向链表,创建,查找,删除 6 */ 7 //定义结构 8 typedef struct stu 9 { 10 char name[30]; 11 char sex; 12 int num; 13 float math; 14 float chinese; 15 float english; 16 }STU; 17 typedef struct node 18 { 19 STU data; 20 struct node *pre; 21 struct node *next; 22 }NODE; 23 //创建空链表 24 NODE *creatList() 25 { 26 NODE *head = (NODE *)malloc(sizeof(NODE)); 27 head->pre = head;//自己指向自己,形成回环,自己指向自己很重要。后面插入节点都靠他。 28 head->next = head; 29 return head; 30 } 31 //插入节点 32 void insertNode(NODE *head) 33 { 34 NODE * cur = (NODE *)malloc(sizeof(NODE)); 35 printf("------------input student score---------------\n"); 36 printf("pls input name :"); scanf("%s",cur->data.name);getchar(); 37 printf("pls input sex :"); scanf("%c",&cur->data.sex); 38 printf("pls input num :"); scanf("%d",&cur->data.num); 39 printf("pls input math :"); scanf("%f",&cur->data.math); 40 printf("pls input chinese :"); scanf("%f",&cur->data.chinese); 41 printf("pls input english :"); scanf("%f",&cur->data.english); 42 cur->next = head->next; 43 cur->pre = head; 44 head->next = cur; 45 cur->next->pre = cur; 46 } 47 //遍历链表 48 void traverList(NODE *head) 49 { 50 NODE *phead = head->next; 51 while(phead != head) 52 { 53 printf("name:%s sex:%c num:%d math:%.2f chinese:%.2f english:%.2f\n" 54 ,phead->data.name,phead->data.sex,phead->data.num,phead->data.math,phead->data.chinese,phead->data.english); 55 phead = phead->next; 56 } 57 } 58 NODE * searchList(NODE *head,char *p) 59 { 60 NODE *phead = head->next; 61 while(phead != head) 62 { 63 if(strcmp(p,phead->data.name) == 0) 64 return phead; 65 phead = phead->next; 66 } 67 } 68 void deleteNode(NODE *p) 69 { 70 p->pre->next = p->next; 71 p->next->pre = p->pre; 72 } 73 int main(void) 74 { 75 //创建空链表 76 NODE * head = creatList(); 77 //插入节点 78 int i; 79 for(i = 0;i<4;i++) 80 insertNode(head); 81 traverList(head); 82 //查找结点 83 NODE *p =searchList(head,"haha"); 84 //删除结点 85 printf("------------delete---------------\n"); 86 deleteNode(p); 87 traverList(head); 88 89 90 return 0; 91 }