目录
建立节点
typedef struct node { char name[20]; //姓名 int number; //学号 struct node* next;//指针域 }Node;
初始化
Node* InitList() { Node* head; head = (Node*)malloc(sizeof(Node)); head->next = NULL; return head; }
尾插法建立单链表
void CreatByRear(Node* head) { Node* r, * s; char name[20]; int number; r = head; while (1) { scanf("%s", name); scanf("%d", &number); if (number == 0) break; s = (Node*)malloc(sizeof(Node)); strcpy(s->name, name); s->number = number; r->next = s;//原来的节点指向新节点 r = s;//r指向新的节点 } r->next = NULL; }
头插法建立单链表
void CreatByHead(Node* head) { Node* s; char name[20]; int number; printf("请输入学生的姓名和学号"); while (1) { scanf("%s", name); scanf("%d", &number); if (number == 0) break; s = (Node*)malloc(sizeof(Node)); strcpy(s->name, name); s->number = number; s->next = head->next; head->next = s; } }
单链表的遍历
void OutPut(Node*head) { Node* p = head->next; while (p) { printf("姓名: %s\n", p->name); printf("学号: %d\n\n\n", p->number); p = p->next; } }
单链表的查询
Node* FindNote(Node* head,int x)//查找第x个节点(包含头节点) { Node* p = head; while (p && x > 1) { p = p->next; x--; } if (!p) { printf("该节点不存在"); } else return p; }
单链表的删除
void Delete(Node* head, int i) { if (i == 1)//头删 { Node* cur = head->next; head->next = cur->next; free(cur); return; } Node* p = FindNote(head, i-1); Node* q= FindNote(head, i); p->next = q->next; free(q); }
单链表的插入
void Insert(Node* head, int i) { printf("请输入要插入学生的姓名和学号"); scanf("%s", s->name); scanf("%d", &s->number); Node* s = (Node*)malloc(sizeof(Node)); Node* p = FindNote(head, i); if (k == 1)//头插 { s->next = head->next; head->next = s; return; } s->next = p->next; p->next = s; }
单链表的逆序(三指针法)
void Reverse(Node* head) { Node* p,* q, *r=NULL; p = head->next; q = p->next; p->next = NULL; while (q) { r = q; q = q->next; r->next = p; p = r; } head->next = r; }
链表的销毁
//链表的销毁 void DestoryList(Node*head) { Node* p = head->next; Node* q = p; while (p) { p = p->next; free(q); q = p; } }