44 lines
893 B
C++
44 lines
893 B
C++
#include<stdio.h>
|
||
#include<stdlib.h>
|
||
struct node {
|
||
int data;
|
||
struct node *next;
|
||
};
|
||
|
||
int main (){
|
||
struct node *head, *p, *q, *t;
|
||
int a,n;
|
||
head=NULL;
|
||
scanf("%d",&n);
|
||
for(int i = 1;i <= n; i++){
|
||
scanf("%d",&a);
|
||
p=(struct node*)malloc(sizeof(struct node));
|
||
p->data=a;
|
||
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==NULL||t->next->data>a) { //当到链表的结尾或者当前节点的下一个节点的值大于a时,将a插入链表
|
||
p=(struct node *)malloc(sizeof(struct node)); //创建临时节点p来存储输入的信息
|
||
p->data=a;
|
||
p->next=t->next; //临时节点与当前节点的下一个节点进行链接
|
||
t->next=p; //将临时节点链接在当前节点的尾部
|
||
break; //插入完成,退出循环。
|
||
}
|
||
t=t->next;
|
||
}
|
||
t=head;
|
||
while(t!=NULL) {
|
||
printf("%d ",t->data);
|
||
t=t->next;
|
||
}
|
||
return 0;
|
||
}
|
||
|