1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
//单链表
#include <stdio.h>
#include <stdlib.h>

#define TRUE 1
#define FALSE 0

typedef struct Node //定义一个结点的数据结构
{
int data; //数据
struct Node* next; //指向下一个结点的指针
} Node;

Node* initList() //创建链表头
{
Node* list = (Node*)malloc(sizeof(Node)); //开辟空间
list ->data = 0; //头结点值为0
list ->next = NULL; //头结点 指向 NULL
return list;

}

void headInsert(Node* list, int data) //头插法
{
Node* node = (Node*)malloc(sizeof(Node)); //开辟空间
node -> data = data; //给新结点赋值
node -> next = list -> next; //新结点的指针 指向 下一个结点
list -> next = node; //头结点的指针 指向 新结点
list -> data++; //头结点数据++,代表链表中的结点增多
}

void tailInsert(Node* L, int data)
{
Node* node = L; //将头结点赋值给node
for(int i = 0; i < L -> data; i++) //遍历原来的尾结点,i<非头结点的结点数量
{
node = node->next; //两个非头结点移一次,
}
Node* n = (Node*)malloc(sizeof(Node)); //给新结点开辟内存空间
n -> data = data; //给新结点赋值
n -> next = NULL; //将新结点指向NULL
node -> next = n; //原来的为节点node指向 新的尾结点n
L -> data ++; //头结点的值++
}

void delete(Node* L, int data) //删除结点
{
Node* preNode = L; //将头结点赋值给preNode
Node* node = L -> next; //将头结点的指向的地址赋给 node
while(node) //当node的地址不为空时
{
if(node -> data == data) //判断node的值是否等于要删除的值
{
preNode -> next = node -> next; //将目标结点指向的地址 赋值给 上一个结点的指针
free(node); //释放空间
L -> data--; //链表个数--
return TRUE;
}
preNode = node; //不等于,头节点等于node
node = node -> next; //不等于,node等于node指向的结点
}
return FALSE;

}

void printList(Node* L) //打印链表中的数据
{
Node* node = L -> next; //将头节点指向的结点赋值给node
while(node) //当node不是尾结点时
{
printf("node = %d \n",node -> data); //打印node的值
node = node -> next; //更新node的结点
}

}

int main()
{
printf("Hello world!\n");
Node* list = initList();
headInsert(list,1);
headInsert(list,2);
headInsert(list,3);
headInsert(list,4);
headInsert(list,5);
tailInsert(list,6);
tailInsert(list,7);
tailInsert(list,8);
tailInsert(list,9);
tailInsert(list,10);
printList(list);
delete(list,9);
printList(list);
return 0;
}