编写一个函数,要求按数据域中数据从小到大的顺序建立链表并输出。
函数接口定义:
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
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);
}
完整代码
#include <stdio.h>
#include <malloc.h>
struct Node
{
int num;
struct Node *next;
};
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);
}
void print(struct Node *head)
{
struct Node *p=head;
while (p!=NULL)
{
printf("%d ",p->num);
p=p->next;
}
printf("\n");
}
int main()
{
struct Node *head;
head=create();
print(head);
return 0;
}
本文介绍了一个函数,该函数用于创建一个链表,并确保链表中的元素按升序排列。通过读取一系列整数输入,函数创建链表,然后使用冒泡排序算法调整链表节点的顺序,最后输出排序后的链表。
3797

被折叠的 条评论
为什么被折叠?



