单链表的基本操作

#include <stdio.h>
#include <malloc.h>
typedef struct Link{
	Link *next;
	int data;
}link;

link* createLink()
{
	link *head,*p,*s;
	head=(link*)malloc(sizeof(link));
	p=head;
	int cycle=1;
	int a=0;
	while(cycle)
	{
		printf("please input the data\n");
		scanf("%d",&a);
		if(a!=0)
		{
			s=(link*)malloc(sizeof(link));
			s->data=a;
			p->next=s;
			p=s;
		}
		else
			cycle=0;
	}
	head=head->next;
	p->next=NULL;
	return head;
}

int linkLen(link *head)
{
	if(head==NULL)
		return 0;
	int count=0;
	while(head!=NULL)
	{
		count++;
		head=head->next;
	}
	return count;
}

link* linkDel(int a,link *head)//删除
{
	if(head==NULL)
		return NULL;
	link *tmp=head->next;
	link *res=head;
	if(head->data==a)
		return tmp;
	while(tmp!=NULL)
	{
		if(tmp->data==a)
			res->next=tmp->next;
		res=res->next;
		tmp=tmp->next;
	}
	return head;
}

link* insertLink(link *head,int a)//插入
{
	link *p=(link*)malloc(sizeof(link));
	p->data=a;
	link *pre,*last;
	pre=head;
	while(a>pre->data&&pre->next!=NULL)
	{
		last=pre;
		pre=pre->next;
	}
	if(a<=pre->data)
	{
		if(head==pre)//insert before the head
		{
			p->next=pre;
			head=p;
		}
		else//in the middle of link
		{
			last->next=p;
			p->next=pre;
		}

	}
	else//at the end of the link
	{
		pre->next=p;
		p->next=NULL;
	}
	return head;
}

link* reverse(link *head)//反转
{
	link *pre,*temp;
	pre=NULL;
	if(head==NULL||head->next==NULL)
		return head;
	while(head->next!=NULL)
	{
	temp=head->next;
	head->next=pre;
	pre=head;
	head=temp;
	}
	head->next=pre;
	return head;
}

void linkPrintf(link *head)
{
	int len=linkLen(head);
	while(len--)
	{
		printf("%d ",head->data);
		head=head->next;
	}
	printf("\n");
}
int main()
{
	link *head;
	head=createLink();
	linkPrintf(head);
	head=insertLink(head,4);
	linkPrintf(head);
	head=linkDel(4,head);
	linkPrintf(head);
	head=reverse(head);
	linkPrintf(head);
	int n=linkLen(head);
	printf("%d\n",n);
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值