链表的一些基本操作

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

struct Node
{
	int data;
	struct Node *next;
};
struct Node *create()    //头插法,逆序构成链表
{
	struct Node *head,*p;
	head=NULL;
	int x;
	while(scanf("%d",&x)&&x!=-1)
	{
		p=(struct Node*)malloc(sizeof(struct Node));    
		p->data=x;
		p->next=head;
		head=p;
	}
	return head;
}

struct Node* create2()
{
	struct Node* head,*p,*q;    //尾插法,正序构成链表,q为辅助滚动指针,用于连接
	int x;
	while(scanf("%d",&x)&&x!=-1)
	{
		p=(struct Node*)malloc(sizeof(struct Node));
		p->data=x;
		p->next=NULL;
		if(head==NULL)
		{
			head=q=p;
		}
		else{
			q->next=p;
			q=p;
		}
	}
	return head;
}
void output(struct Node *head)
{
	struct Node* p;
	p=head;
	while(p!=NULL)
	{
		printf("%d ",p->data);
		p=p->next;
	}
	printf("\n");
}
struct Node* insert(struct Node* head,int x)
{
	struct Node *p,*q;
	p=(struct Node* )malloc(sizeof(struct Node));
	p->data=x;
	if(head==NULL||head->data>x)    //头空或要插在头部
	{
		p->next=head;
		head=p;
		return head;
	}
	q=head;
	while(q->next!=NULL &&q->next->data<x)
	{
		q=q->next;            //q指针滚动
	}
	p->next=q->next;        
	q->next=p;
	return head;
}
struct Node* del(struct Node* head,int x)
{
	struct Node *p,*q;
	if(head==NULL)	return head;        //空表无删
	if(head->data==x)               //删头,free
	{
		q=head;
		head=head->next;
		free(q);
		return head;
	}
	p=head;
	while(p->next!=NULL&&p->next->data!=x)
	{
		p=p->next;
	}
	if(p->next!=NULL)        //如果有删的
	{
		q=p->next;
		p->next=q->next;
		free(q);
	}
	return head;        //没有直接返回了
}
int main()
{
	int x,y;
	struct Node *head;
	head=create();
	output(head);
	head=create2();
	output(head);
	head=insert(head,x);
	output(head);
	head=del(head,y);
	output(head);
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值