PTA 数据结构与算法 7-51 两个有序链表序列的合并

如有不对,不吝赐教
进入正题:
已知两个非降序链表序列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<stdio.h>
#include<malloc.h>

struct ListNode{
int data;
struct ListNode *next;
};

struct List{
struct ListNode *head;
struct ListNode *tail;
};

void AddNode(struct List *S,int data);
void Insert(struct List *S1,struct List *S2);
void Print(struct List *S);

int main(void)
{
    struct List *S1,*S2;  //S1,S2两个费降序链表头部信息
    int input;

    S1=(struct List *)malloc(sizeof(struct List));
    S1->head=(struct ListNode *)malloc(sizeof(struct ListNode));
    S2=(struct List *)malloc(sizeof(struct List));
    S2->head=(struct ListNode *)malloc(sizeof(struct ListNode));
    S1->tail=S1->head;
    S2->tail=S2->head;
    S1->tail->data=S2->tail->data=-1;

    while(scanf("%d",&input),-1!=input)
      AddNode(S1,input);
    while(scanf("%d",&input),-1!=input)
      AddNode(S2,input);


    Insert(S1,S2);
    Print(S1);

    return 0;
}

void AddNode(struct List *S,int data)
{
    struct ListNode *newOne;
    newOne=(struct ListNode *)malloc(sizeof(struct ListNode));
    newOne->next=NULL;

    S->tail->data=data;
    S->tail->next=newOne;
    S->tail=newOne;

    return ;
}

void Insert(struct List *S1,struct List *S2)
{
    struct ListNode *cur=S1->head;
    struct ListNode *temp;

    if(cur->data==-1){
      S1->head=S2->head;
      S1->tail=S2->tail;
      free(S2);
      S2=NULL;
      return ;
    }

    while(cur->next!=S1->tail){
      if(cur->data<=S2->head->data&&cur->next->data>=S2->head->data){
        temp=S2->head;
        S2->head=S2->head->next;   //变换S2
        temp->next=cur->next;
        cur->next=temp;       //插入到S1链表中
      }
      cur=cur->next;         //向后走
    }

    if(S2->head!=S2->tail){
      cur->next=S2->head;
      free(S1->tail);
      S1->tail=S2->tail;
    }      //说明还有S2的链表没连上

    free(S2);
    S2=NULL;

    return ;
}

void Print(struct List *S)
{
    struct ListNode *cur=S->head;

    if(cur==S->tail){
      printf("NULL");
      return ;
    }

    while(cur->next!=S->tail){
      printf("%d ",cur->data);
      S->head=S->head->next;
      free(cur);
      cur=NULL;
      cur=S->head;
    }

    printf("%d",cur->data);
    free(cur);
    free(S);
    cur=NULL;
    S=NULL;

    return ;
}

测试结果:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值