PTA-两个有序链表序列的合并

该博客介绍如何合并两个非降序链表S1和S2,形成一个新的非降序链表S3。输入和输出格式分别给出,内容涉及链表操作和排序。

已知两个非降序链表序列S1与S2,设计函数构造出S1与S2的并集新非降序链表S3。

输入格式:

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

输出格式:

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

代码:

 /*
  @两个有序链表序列的合并
 */
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
typedef  struct List{
    int data;
    struct List *next;
}List,*list;

void ListInit(list &L){
    list p = (list)malloc(sizeof(List));
	L = p;
}

list CreatList(){
        list head = (list)malloc(sizeof(list));
        head->next = NULL;
        list p,t;
        int a ;
		scanf("%d",&a);
		if(a==-1){
			return NULL;
		}
		else{
        while(true){
            if(a!=-1){
                    t=(list)malloc(sizeof(struct List));
                    t->data=a;
                    if(head->next==NULL){
                         head->next = t;
                    }
                    else{
                         p->next=t;
                    }
                    p=t;
            }
            else{
                p->next=NULL;     //一定要有此部分结束,否则传值无底线
                break;
            }
			scanf("%d",&a);
        }
            return head;
	}
}

int Lengthlist(list &L){
        list p = L->next;
        int length = 0;
        while(p){
            length++;
            p = p->next;
        }
        return length;
}

list MergeList(list a,list b){       //合并两链表且不含重复元素
	list la = a->next,lb = b->next;
	list c,lc;
	lc = c = a;            //lc取a的地址
        while(la&&lb){
            if(la->data<=lb->data){
                c->next = la ; c = la; la = la->next;
            }
            else{
                c->next = lb; c = lb;  lb = lb->next;
            }
        }
        c->next = la?la:lb;
        return  lc;         // 返回新表c的头节点
}

void  PrintList(list &L){
        list p = L->next;
		int flag = 0;
        while(p!=NULL){
            if(!flag){
             	printf("%d",p->data);
             	flag = 1;
		    }
		    else{
		  	    printf(" %d",p->data);
		    }
          		p = p->next;
        }
}

int main(int argc, char** argv) {
        list d;
	    ListInit(d);
        list a = CreatList();     //a链表
        list b = CreatList();    //b链表
        	if(!a&&!b){
			printf("NULL\n");
		}
		else{
			d = MergeList(a,b);
			PrintList(d);
		}
        return 0;
  }

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值