C语言单向环形链表

#include<stdio.h>
#include<stdlib.h>

struct list 
{
	int data;
	struct list *next;
};

struct list* Create()
{
	struct list *head,*pnew,*end;
	int number = 10;
	int i;
	head = (struct list*)malloc(sizeof(struct list));
	head->data = 0;
	head->next = NULL;
	end = head;
	for(i=1;i<number;i++)
	{
		pnew = (struct list*)malloc(sizeof(struct list));
		pnew->data = i;
		pnew->next = NULL;
		end->next = pnew;
		end = end->next;
	}
	pnew->next = head;//最后一个节点的指针指向head
	return head;
}

struct list* Insert(struct list *head,int pos)
{
	struct list *pnew,*end,*temp;
	int i;
	pnew = (struct list*)malloc(sizeof(struct list));
	pnew->data = 100;
	if(pos==0)//在0的位置插入,就相当于在尾部追加
	{
		temp = head;
		do
		{
			temp = temp->next;
		}while(temp->next!=head);
		temp->next = pnew;
		pnew->next = head;
		head = pnew;
	}
	else
	{
		end = head;
		if(pos>=2)
		{
			for(i=0;i<(pos-1);i++)
			{
				end = end->next;
			}
		}
		pnew->next = end->next;
		end->next = pnew;
	}
	return head;
}

struct list* Delete(struct list *head,int pos)
{
	struct list *obj,*pre,*temp;
	int i;
	if(pos==0)
	{
		pre = head;
		do
		{
			pre = pre->next;
		}while(pre->next!=head);//找到最后一个链节,也就是head前一个链节
		temp = head->next;
		pre->next = head->next;
		free(head);
		head = temp;
	}
	else
	{
		obj = head;
		if(pos>=1)
		{
			for(i=0;i<pos;i++)
			{
				pre = obj;//记录前一个链节
				obj = obj->next;
			}
		}
		pre->next = obj->next;
		if(obj==head)
			head = head->next;//如果被删除的是head,那么新head为原head下一个链节
		free(obj);
	}
	return head;
}

void Print(struct list *head)
{
	struct list *temp;
	temp = head;
	printf("%d\n",temp->data);
	do
	{
		temp = temp->next;
		printf("%d\n",temp->data);
	}while(temp->next!=head);//如果再次循环到head处,则停止输出
}

int Check(struct list *head,int pos)
{
	int i;
	if(pos>=1)
	{
		for(i=0;i<pos;i++)
			head = head->next;
	}
	return head->data;
}

void Modify(struct list *head,int pos,int dat)
{
	int i;
	if(pos>=1)
	{
		for(i=0;i<pos;i++)
			head = head->next;
	}
	head->data=dat;
}

void main()
{
	struct list *head;
	head = Create();
	Modify(head,5,300);
	Print(head);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值