在有序单链表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;
}