在有序单链表L中插入数值x,仍然有序。

附带一张我的运行图作为参考

在有序单链表L中插入数值x,仍然有序。(输入单链表数值时需要从小到大输入)

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

typedef struct node//结点结构定义
{
	int data;//数据域
	struct node *next;//指针域
}LNode;

LNode *CreateLinkList()//尾部插入法创建单链表
{
	LNode *L,*R,*p;
	int x;
    L=(LNode *)malloc(sizeof(LNode));
    L->next=NULL;
	R=L;
	scanf("%d",&x);
	while(x!=0)
	{
		p=(LNode *)malloc(sizeof(LNode));
		p->data=x;
		p->next=NULL;
		R->next=p;
		R=p;
		scanf("%d",&x);
	}
	return L;
}
void PrintLinkList(LNode *L)//打印输出
{
	LNode *p;
	p=L->next;
	while(p!=NULL)
	{
		printf("%4d",p->data);
		p=p->next;
	}
}

LNode *InsertorderLink(LNode *L,int x)//<shang>插入数值X
{
	LNode *p,*q;
	q=(LNode *)malloc(sizeof(LNode));
	p=L;
	while(p->next->data < x)
	{
		p=p->next;
	}
	q->data=x;
	q->next=p->next;
	p->next=q;
	return L;
}
int main()
{
	LNode *L;
	int x;
	printf("输入一组数据(输入0时结束):\n");
	L=CreateLinkList();
	printf("单链表为:\n");
	PrintLinkList(L);
	printf("\n");
	printf("输入要插入的数值:\n");
	scanf("%d",&x);
	L=InsertorderLink(L,x);
	printf("\n");
	printf("插入后的数据为:\n");
	PrintLinkList(L);
	return 0;
}


评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值