数据结构之循环链表

#include<stdio.h>
#include<stdlib.h>
#define OK 0
#define ERROR 1

typedef struct Node
{
int data;
struct Node* next;
}Node;
typedef struct Node linkList;

linkList* create_list(); //创建链表
linkList* tail_list(linkList* cir); //尾插法
int search_list(linkList* cir, int i, int* data); //查找链表
int insert_list(linkList* cir, int i, int data); //插入链表
int delete_list(linkList* cir, int i, int* data); //删除链表
void print_list(linkList* scirq); //打印链表

linkList* create_list()
{
linkList* cir = (linkList*)malloc(sizeof(Node));
if (cir == NULL) {
printf(“申请失败\n”);
return NULL;
}
cir->next = NULL;
return cir;
}

linkList* tail_list(linkList* cir)
{
linkList* s = cir;
linkList* p = NULL;
for (int i = 0; i < 10; i++) {
p = (linkList*)malloc(sizeof(Node));
p->data = i;
s->next = p;
s = p;
}
s->next = cir->next;
return cir;
}

void print_list(linkList* cir)
{
linkList* s = cir;
do {
s = s->next;
printf(“%d\t”, s->data);
} while (s->next != cir->next);
printf(“\n”);
return;
}

int search_list(linkList* cir, int i, int* data)
{
int j = 0;
linkList* p = cir;
do {
p = p->next;
j++;
} while (p->next != cir->next && j < i);

*data = p->data;

return 0;

}

int insert_list(linkList* cir, int i, int data)
{
linkList* node = NULL;
linkList* p = NULL;
int j = 0;
if (i == 0) {
p = cir->next;
while (p->next != cir->next) {
p = p->next;
}
node = (linkList*)malloc(sizeof(Node));
node->data = data;
node->next = cir->next;
cir->next = node;
p->next = node;
return OK;
}
else {
p = cir;
j = 1;
do {
p = p->next;
} while (p->next != cir->next && i >j++);

	node = (linkList*)malloc(sizeof(Node));
	node->data = data;
	node->next = p->next;
	p->next = node;
}
return 0;

}

int delete_list(linkList* cir, int i, int* data)
{
linkList* node = NULL;
linkList* p = NULL;
int j = 0;
if (i == 1) {
p = cir->next;
while (p->next != cir->next) {
p = p->next;
}
node = cir->next;
*data = node->data;
cir->next = node->next;
p->next = cir->next;
free(node);
node = NULL;
return OK;
}
else {
p = cir;
j = 1;
do {
p = p->next;
j++;
} while (p->next != cir->next && j < i);
if (p->next == cir->next) {
printf(“位置非法\n”);
return ERROR;
}
node = p->next;
data = node->data;
p->next = node->next;
free(node);
node = NULL;
}
return 0;
}
int main()
{
linkList
cir = NULL;
int data = 0;
cir = create_list();
cir = tail_list(cir);
print_list(cir);

search_list(cir, 4, &data);
printf("查找的数: %d\n", data);

insert_list(cir, 0, 520);
print_list(cir);

delete_list(cir, 4, &data);
printf("删除的数: %d\n", data);
return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值