Files
python/C++课程/待整理知识/啊哈算法/p52.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

44 lines
893 B
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#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;
}