数据结构 2.2 单循环链表-CSDN博客
阿里云国内75折 回扣 微信号:monov8 |
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6 |
2.单循环链表
data|next——>data|next——>data|next——>头节点
1.初始化链表
2.增加节点头插法、尾插法
3.删除节点
4.遍历链表
定义一个链表结构体定义一个数据结构存放data域和指针域
typedef struct Node {//定义一个结构体存放data域和指针域
int data;//数据域类型
struct Node* next;
}Node;//定义一个链表Node
初始化链表
Node* initList() {//初始化链表
Node* L = (Node*)malloc(sizeof(Node));//开辟空间 L头指针
L->data = 0;//data域
L->next = L;//下一个节点指向
return L;
}
头插法
void headInsert(Node* L, int data) {//头插法 传入头指针L
Node* node = (Node*)malloc(sizeof(Node));//创建指针变量并开辟空间
node->data = data;
node->next = L->next;//头指针指向新节点 新节点指向原先头节点
L->next = node;
}
尾插法
void tailInsert(Node* L, int data) {//尾插法
Node* n = L;//链表L
Node* node = (Node*)malloc(sizeof(Node));//新建指针变量
node->data = data;
while (n->next != L) {//判断是否是最后一个节点
n = n->next;
}
node->next = L;//指针变量指向L
n->next = node;//n指向的next等于node
}
删除
#define TRUE 1
#define FALSE 0
int Delete(Node* L, int data)//删除
{
Node* preNode = L;//记录每次循环的前一个结点
Node* node = L->next;
while (node != L)
{
if (node->data == data) {
//delete
preNode->next = node->next;
free(node);
return TRUE;
}
preNode = node;//如果没有的话
node = node->next;
}
return FALSE;
}
遍历链表
void printList(Node* L) {//遍历链表
Node* node = L->next;//定义一个链表给他赋值L链表
while (node != L) {//链表不为空
printf("%d->", node->data);//打印
node = node->next;//node指向node的next指针
}
printf("NULL\n");
}
main函数
int main()
{
Node* L = initList();
headInsert(L, 1);
headInsert(L, 2);
headInsert(L, 3);
headInsert(L, 4);
headInsert(L, 5);
tailInsert(L, 6);
tailInsert(L, 7);
tailInsert(L, 8);
tailInsert(L, 9);
tailInsert(L, 10);
printList(L);
Delete(L, 4);
Delete(L, 5);
printList(L);
return 0;
}
单循环链表函数
typedef struct Node {//定义一个结构体存放data域和指针域
int data;//数据域类型
struct Node* next;
}Node;
Node* initList() {//初始化链表
Node* L = (Node*)malloc(sizeof(Node));
L->data = 0;
L->next = L;
return L;
}
void headInsert(Node* L, int data) {//头插法
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
node->next = L->next;
L->next = node;
}
void tailInsert(Node* L, int data) {//尾插法
Node* n = L;
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
while (n->next != L) {
n = n->next;
}
node->next = L;
n->next = node;
}
#define TRUE 1
#define FALSE 0
int Delete(Node* L, int data)//删除
{
Node* preNode = L;
Node* node = L->next;
while (node != L)
{
if (node->data == data) {
//delete
preNode->next = node->next;
free(node);
return TRUE;
}
preNode = node;
node = node->next;
}
return FALSE;
}
void printList(Node* L) {//遍历链表
Node* node = L->next;
while (node != L) {
printf("%d->", node->data);
node = node->next;
}
printf("NULL\n");
}
int main()
{
Node* L = initList();
headInsert(L, 1);
headInsert(L, 2);
headInsert(L, 3);
headInsert(L, 4);
headInsert(L, 5);
tailInsert(L, 6);
tailInsert(L, 7);
tailInsert(L, 8);
tailInsert(L, 9);
tailInsert(L, 10);
printList(L);
Delete(L, 4);
Delete(L, 5);
printList(L);
return 0;
}
运行结果