PTA 第8章结构体与其他结构类型作业 6-4 增加结点建立升序链表 (10分)

本文介绍了一个函数,该函数用于创建一个链表,并确保链表中的元素按升序排列。通过读取一系列整数输入,函数创建链表,然后使用冒泡排序算法调整链表节点的顺序,最后输出排序后的链表。

编写一个函数,要求按数据域中数据从小到大的顺序建立链表并输出。
函数接口定义:
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;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值