编写一个函数,要求按数据域中数据从小到大的顺序建立链表并输出。
函数接口定义:
struct Node *create();
函数create,每个结点连接时保持升序。
裁判测试程序样例:
解释
#include <stdio.h>
#include <malloc.h>
struct Node
{
int num;
struct Node *next;
};
struct Node *create();
void print(struct Node *head);
int main()
{
struct Node *head;
head=create();
print(head);
return 0;
}
void print(struct Node *head)
{
struct Node *p=head;
while (p!=NULL)
{
printf("%d ",p->num);
p=p->next;
}
printf("\n");
}
/* 你的代码将被嵌在这里 */
输入样例:
2 4 6 8 7 5 3 1 -1
输出样例:
1 2 3 4 5 6 7 8
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
struct Node *create()
{
struct Node *p1,*p2,*head;
p1=p2=(struct Node*)malloc(sizeof(struct Node));
int n=0;
head=NULL;
scanf("%d",&p1->num);
while(p1->num!=-1)
{
n++;
if(n==1)
head=p1;
else
p2->next=p1;
p2=p1;
p1=(struct Node*)malloc(sizeof(struct Node));
scanf("%d",&p1->num);
}
p2->next=NULL;
struct Node temp,*p,*q;
for(p=head;p!=NULL;p=p->next)
{
for(q=head;q!=NULL;q=q->next)
{
if(p->num<q->num)
{
temp.num=p->num;
p->num=q->num;
q->num=temp.num;
}
}
}
return(head);
}