// 循环双链表:在双链表的基础上让尾节点的next指向头节点,头节点的头指针指向尾节点
#include <stdio.h>
#include <stdlib.h>
// 链表构造
typedef struct Node
{
int data;
struct Node* pre;//头指针
struct Node* next;//尾指针
}Node;
// 初始化
Node* initList()
{
Node* list = (Node*)malloc(sizeof(Node));
list->data = 0;
list->pre = list;
list->next = list;//头指针和尾指针都指向自身
return list;
}
// 头插
void headInsert(Node* list, int data)
{
// 开辟空间,创建节点
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
node->next = list->next;//对新节点头尾指针操作
node->pre = list;
// 这里不需要进行判断,因为链表循环,所以头节点后面还有节点,只不过还是头节点罢了
list->next->pre = node;
list->next = node;
list->data++;
}
// 尾插
void tailInsert(Node* list, int data)
{
// 开辟空间,创建节点
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
Node* current = list->next;//指向第一个节点
// 从第一个节点开始遍历,找到尾节点
while(current->next != list)
{
current = current->next;
}
node->next = current->next;//对新节点的头尾指针进行链接
node->pre = current;
list->pre = node;//对指向尾节点的指针进行修改
current->next = node;
list->data++;
}
// 删除
void delete(Node* list, int data)
{
// Node* pre = list;不需要保存前一个节点了,因为current有头指针,可以找到前一个节点
Node* current = list->next;
while (current != list)
{
if (current->data == data)
{
current->pre->next = current->next;//调整前一个指针next指向
current->next->pre = current->pre;//调整后一个指针pre指向
free(current);
current = NULL;
printf("已删除!\n");
list->data--;
return;
}
current = current->next;
}
printf("没找到!\n");
}
// 打印
void printList(Node* list)
{
Node* current = list->next;//指向第一个头节点
while (current != list)
{
printf("%d->", current->data);
current = current->next;
}
printf("NULL\n");
}
int main(int argc, char const *argv[])
{
// 初始化
Node* list = initList();
// 头插
headInsert(list, 1);
headInsert(list, 2);
headInsert(list, 3);
// 打印
printList(list);
// 尾插
tailInsert(list, 4);
tailInsert(list, 5);
tailInsert(list, 6);
// 打印
printList(list);
delete(list, 3);
delete(list, 5);
printList(list);
return 0;
}
08-07
4342
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交