增加结点建立升序链表

本文介绍了一个编程题目,要求编写一个函数,接收用户输入的一系列整数,按升序创建链表并输出。函数`create`负责处理输入,确保链表中的节点值按顺序排列。
摘要由CSDN通过智能技术生成

编写一个函数,要求按数据域中数据从小到大的顺序建立链表并输出。

函数接口定义:

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值