单项循环链表

 单项循环链表的增删查改

#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 ;
		}
		

	}
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值