CLinkList(循环单链表)

本文提供了一个使用C语言实现的循环链表示例,包括创建、查找、插入及删除等基本操作。通过具体代码展示了如何对循环链表进行管理和维护。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<stdio.h>
typedef int Datatype;
typedef struct link_node {
Datatype info;
struct link_node *next;
}node;


node *init()
{
return NULL;
}


void display(node *head)
{
if (!head)
printf("链表为空,无法进行输出!\n");
else
{
node *p = head;
while (p->next!=head)
{
printf("%5d", p->info);
p = p->next;
}
if(p->next == head)
printf("%5d", p->info);
}
}


node *find(node *head, int i)
{
node *p = head;
int j = 2;;
if (i == 1)
return head;
else
{
p = p->next;
while (p->next!=head&&i != j)
{
p = p->next;
++j;
}
if (p->next == head&&i != j)
{
printf("没有找到第%d个结点\n", i);
return NULL;
}
else
if (i == j)
return p;
}
}


node *find_last(node *head)
{
node *p = head;
while (p->next!=head)
p = p->next;
return p;
}


node *insert(node *head, Datatype x, int i)
{
node *p,*last;
node *q = (node *)malloc(sizeof(node));
q->info = x;
q->next = NULL;
if (i == 0)
{
last = find_last(head);
q->next = head;
head = q;
last->next = head;
}
else
{
p = find(head, i);
if (p)
{
q->next = p->next;
p->next = q;
}
}
return head;
}


node *build(node *head, Datatype x)
{
node *p, *q;
p = (node *)malloc(sizeof(node));
p->info = x;
if (head == NULL)
{
head = p;
head->next = head;
}
else
{
q = find_last(head);
q->next = p;
p->next = head;
}
return head;
}


node *dele(node *head, Datatype x)
{
node *p = head, *pre = init(&pre);
if (!p)
printf("链表为空,无法进行删除!\n");
else
{
while (p->next!=head&&p->info != x)
{
pre = p;
p = p->next;
}
if (p->next == head&&p->info != x)
printf("没有找到要删除的值!\n");
else
if (p->info == x)
pre->next = p->next;
}
return head;
}


void main()
{
node *head;
head = init();
int i=0;
node *f;
for (i = 0; i<10; i++)
head = build(head,i*2);
display(head);
putchar('\n');
f = find(head, 8);
printf("第8个结点的值为:%d\n", f->info);
head = insert(head, 666, 8);
printf("在第8个结点后插入一个值后链表为:");
display(head);
putchar('\n');
head = dele(head, 8);
printf("删除值为8的结点后链表为:");
display(head);
putchar('\n');
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值