C语言实现的循环单链表

#include"stdlib.h"
typedef struct listnode{
char* data;
struct listnode* next;
}listnode;

listnode* init()
{
listnode* head = (listnode*)malloc(sizeof(listnode));
if (head == NULL){ return; }
head->data = NULL;
head->next = head;
return head;
}
listnode* createnode(char* value)
{
if (value == NULL){ return; }
listnode* tmp = (listnode*)malloc(sizeof(listnode));
if (tmp == NULL){ return; }
tmp->data = value;
tmp->next = NULL;
return tmp;
}

void pushfront(listnode* list,char* value)
{
if (list == NULL||value==NULL)
{
return;
}
listnode* tmp = createnode(value);
tmp->next = list->next;
list->next = tmp;
}

void pushback(listnode* list,char* value)
{
if (list == NULL || value == NULL)
{
return;
}
listnode* tmp =list->next;
while (tmp->next != list)
{
tmp = tmp->next;
}
listnode* pushnode = createnode(value);
tmp->next = pushnode;
pushnode->next = list;

}

void popfront(listnode* list)
{
if (list == NULL){ return; }
listnode* tmp = list->next;
list->next = tmp->next;
free(tmp);
}
void popback(listnode* list)
{
if (list == NULL){ return; }
listnode* tmp1 = list;
listnode* tmp2 = NULL;
while (tmp1->next->next!=list)
{
tmp1 = tmp1->next;
}
tmp2 = tmp1->next;
tmp1->next = tmp1->next->next;
free(tmp2);
}
void insert(listnode* list, char* value, int pos)
{
if (list == NULL || value == NULL || pos<0){ return; }
int length = getlength(list);
if (pos >length+1)
{
pos = length+1;
}
listnode* tmp = list;
for (int i = 1; i<pos; i++)
{
tmp = tmp->next;
}
listnode* insertnode = createnode(value);
insertnode->next = tmp->next;
tmp->next = insertnode;
}

int getlength(listnode* list)
{
if (list == NULL)
{
return;
}
int i = 0;
listnode* tmp = list;
for (; tmp->next != list; i++)
{
tmp = tmp->next;
}
return i;
}
int printbylink(listnode* list)
{
if (list == NULL)
{
return;
}
int i = 0;
listnode* tmp = list;
for (; tmp->next != list;i++)
{
tmp = tmp->next;
printf("%s\n",tmp->data);
}
return i;
}

void main(){
listnode* list = init();
pushfront(list,“aaa”);
pushfront(list,“bbb”);
pushfront(list,“ccc”);
pushback(list,“ddd”);
int length1=printbylink(list);
printf(“长度为:%d\n”, length1);
popfront(list);
popback(list);
int length2 = printbylink(list);
printf(“长度为:%d\n”,length2);
insert(list,“1”,2);
insert(list,“2”,100);
insert(list,“3”,1);
int length3 = printbylink(list);
printf(“长度为:%d\n”, length3);
system(“pause”);
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值