单项循环链表的增删查改
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
typedef struct node
{
int data;
struct node *next;
}node;
//创建头节点
node *link_list_init(void);
//添加 头插
void link_list_add(int input,node *head);
//尾插
void link_list_add_tail(int input,node *head);
//遍历
void link_list_show(node *head);
//间隔一秒打印
void link_list_cycle(node *head);
//删除
void link_list_del(int input,node *head);
int main(int argc, char const *argv[])
{
//初始化空链表
node *head=link_list_init();
int input;
//元素个数
while(1)
{
scanf("%d",&input);
if(input>0)
{
//link_list_add(input,head);
link_list_add_tail(input,head);
}
if(input==0)
link_list_cycle(head);
if(input<0)
link_list_del(-input,head);
link_list_show(head);
}
return 0;
}
//创建头节点
node *link_list_init(void)
{
node *p=(node*)malloc(sizeof(node));
if(NULL==p)
{
perror(" \n");
return NULL;
}
p->data=0;
p->next=p;
return p;
}
//添加 尾插
void link_list_add_tail(int input,node *head)
{
node *pos=head;
//找到最后一个元素
while(pos->next!=head)
pos=pos->next;
link_list_add(input,pos);
}
//头插
void link_list_add(int input,node *head)
{
node *p = link_list_init();
p->data=input;
p->next=head->next;
head->next=p;
}
//遍历
void link_list_show(node *head)
{
node *pos=head->next; // 因为头节点不存有效数据,所以遍历时,从第一个有效数据节点开始
for(pos=head->next;pos!=head;pos=pos->next)
{
printf("%d ", pos->data); // 打印数据
}
printf("\n");
}
//间隔1秒输出
void link_list_cycle(node *head)
{
node *pos=head->next;
for(pos=head->next;pos!=head;pos=pos->next)
{
printf("%d\n", pos->data); // 打印数据
sleep(1);
}
return ;
}
//删除
void link_list_del(int input,node *head)
{
if(head->next==head)
printf("没有信息打印\n");
else
{
node *pos=head;
node *pos_del;
for(pos_del=head->next;pos_del!=head;pos_del=pos_del->next)
{
if(pos_del->data==input)
{
pos->next=pos_del->next;
free(pos_del);
break;
}
pos=pos_del;
}
if(pos_del==head)
{
printf("not found\n");
return ;
}
}
}