链表 链表的合并(2022)

7-1 两个有序链表序列的合并
已知两个非降序链表序列S1与S2,设计函数构造出S1与S2合并后的新的非降序链表S3。

输入格式:
输入分两行,分别在每行给出由若干个正整数构成的非降序序列,用−1表示序列的结尾(−1不属于这个序列)。数字用空格间隔。

输出格式:
在一行中输出合并后新的非降序链表,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出NULL。

输入样例:
1 3 5 -1
2 4 6 8 10 -1
输出样例:
1 2 3 4 5 6 8 10

#include<iostream>
using namespace std;

struct node
{
    int num;
    struct node *next;
};

struct node *creat(struct node *head){
    struct node *p,*q;
    int num;
    q = head;
    while(~scanf("%d", &num)){
          if(num == -1){
            break;
          }
          p = (struct node*)malloc(sizeof(struct node));
          p->next = NULL;
          p->num = num;
          q->next = p;
          q = q->next;
          }
    return head;
};

struct node *sort_struct(struct node *head1, struct node *head2)
{
    struct node *p,*p1,*p2,*q1, *q2;
    struct node *head;
    head = (struct node *)malloc(sizeof(struct node));
    p = head;
    q1 = head1;
    q2 = head2;
    p1 = head1 -> next;
    p2 = head2 -> next;
    while(p1!=NULL && p2!=NULL)
    {
        if(p1->num < p2 ->num){
            p -> next = p1;
            q1 -> next = p1->next;
            p1 = q1->next;
        }else{
            p -> next = p2;
            q2 ->next = p2 -> next;
            p2 = q2 -> next;
        }
        p = p -> next;
    }
    if(p1 == NULL){
        p -> next = p2;
    }else{
        p -> next = p1;
    }
    return head;
};

void print(struct node *head)
{
    struct node *p;
    p = head -> next;
    if(head->next == NULL){
        printf("NULL");
    }
    while(p != NULL)
    {
        if(p->next == NULL){
            printf("%d\n", p->num);
        }else{
        printf("%d ", p->num);
        }
        p = p->next;
    }

}

int main()
{
    struct node *head,*head1;
    head = (struct node*)malloc(sizeof(struct node));
    head1 = (struct node*)malloc(sizeof(struct node));
    head = creat(head);
    head1 = creat(head1);
    head = sort_struct(head, head1);
    print(head);
    return 0;
}

做这道题还有一个小小的疑问,就是条件语句的简写形式。
题目中的输出是使用了if —— else 语句。
原来我还学习过一种形式。是形似

printf("%d%c",p->num p->next==NULL?" ":"");
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值