1. 带头结点单链表基本操作
1.1 头文件声明及结构体定义
#include <stdio.h> #include <stdlib.h> typedef struct temp { int data; struct temp *next; }Node;
1.2 输入数据创建单链表,遇0结束
Node *creat() { int data; Node *head, *p, *q; head = (Node *)malloc(sizeof(Node)); head->next = NULL; p = head; while (scanf("%d", &data) && data) { q = (Node *)malloc(sizeof(Node)); q->data = data; q->next = NULL; p->next = q; p = p->next; } return head; }
1.3 单链表测长及打印
int length(Node *head) { int ret = 0; Node *p = head->next; while (p) { p = p->next; ret++; } return ret; } void print(Node *head) { Node *p = head->next; while (p) { printf("%d ", p->data); p = p->next; } printf(" "); }
1.4 删除单链表第 i (0 ≤ i ≤ length-1)个结点
int del(Node *head, int num) { int i = -1; Node *p, *q; p = head;//p->next->next保证第i个结点存在 while(i<num-1 && p->next && p->next->next) { p = p->next; i++; } if (i != num-1) return 0; q = p->next; p->next = q->next; free(q); return 1; }
1.5 在单链表第 i (0 ≤ i ≤ length)个结点前插入一个元素
int insert(Node *head, int num, int data) { int i = -1; Node *p, *q; p = head; while(i<num-1 && p->next) { p = p->next; i++; } if (i != num-1) return 0; q = (Node *)malloc(sizeof(Node)); q->data = data; q->next = p->next; p->next = q; return 1; }
1.6 单链表的排序(冒泡排序)
void sort(Node *head) { int i, j, n, temp, flag = 1; Node *p; n = length(head); for (i = 1; i < n && flag == 1; i++) { flag = 0; p = head->next; for (j = 0; j < n-i; j++) { if (p->data > p->next->data) { flag = 1; temp = p->data; p->data = p->next->data; p->next->data = temp; } p = p->next; } } }
1.7 单链表的逆置
void reverse(Node *head) { Node *p, *q, *s; if (head->next == NULL) return; p = head->next; q = p->next; while (q) { s = q->next; q->next = p; p = q; q = s; } head->next->next = NULL;//注意链表结尾置空。 head->next = p; }
程序验证(未考虑链表的释放)
int main() { Node *head; head = creat(); printf("length of list: %d ", length(head)); printf("element of list: "); print(head); del(head, 0); printf("after delete the 0th number: "); print(head); insert(head, 4, 11); printf("insert 11 before 4th number: "); print(head); sort(head); printf("element of list after sorted: "); print(head); reverse(head); printf("element of list after reverse: "); print(head); return 0; }