#include<stdio.h>
#include<stdlib.h>
typedef struct _node{
int value;
struct _node *next;
}Node;
int main()
{
int i,n,number,a;
Node *head,*p,*q,*t;
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d",&number);
p=(Node*)malloc(sizeof(Node));
p->value=number;
p->next=NULL;
if(head==NULL)
head=p;
else
q->next=p;
q=p;
}//上面部分就是创建列表
scanf("%d",&a);//输入一个数字
t=head;//遍历链表
while(t!=NULL){
if(t->next->value>a){//如果当前结点的下一个结点的值>输入的值就新增一个结点
p=(Node*)malloc(sizeof(Node));//动态申请一个空间用来存放新增结点
p->value=a;//令新增结点的值等于a
p->next=t->next;//新增结点的后继指针指向指向当前结点后继指针所指的结点如a为4,t指向的是 2 3 5中的3,那意思就是将5放在4的后面
t->next=p;//再将t(3)的后面插入4
break;//结束循环!!!
}
t=t->next;
}
t=head;
while(t!=NULL){
printf("%d",t->value);
t=t->next;
}
return 0;
}
用链表实现在一组从大到小的有序数列中插入一个数字仍保持有序的理解
最新推荐文章于 2022-11-09 20:07:35 发布