1222: 基于链表的两个非递减有序序列的合并

问题:

给定两个非递减的整数序列A和B,利用链表表示序列A和B,将A和B合并为一个非递增的有序序列C,序列C允许有重复的数据。要求空间复杂度为O(1)。

输入
多组数据,每组数据有三行,第一行为序列A和B的长度n和m,第二行为序列A的n个元素,第三行为序列B的m个元素(元素之间用空格分隔)。n=0且m=0时输入结束。

输出
对于每组数据输出一行,为合并后的序列,每个数据之间用空格分隔。

测试样例:

输入
5 5
1 3 5 7 9
2 4 6 8 10
5 6
1 2 2 3 5
2 4 6 8 10 12
0 0
输出
10 9 8 7 6 5 4 3 2 1
12 10 8zhu 6 5 4 3 2 2 2 1 

注意,要求显示 空间复杂度为O(1),意味着一定情况下牺牲时间复杂度

而接下来的代码,最差时间复杂度为O(n2),但空间复杂度O(1)

可能学院OJ样例相对较短,故 运行时间 11ms, 内存 1200 KiB,

运行结果相对不错!

#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>

typedef struct SNode *Stack;
struct SNode{
	int data;
	struct SNode *next;
};

Stack read(int n);
void com_fin(int m, Stack S);
void push(int num, Stack S);
Stack find_push(int num, Stack S);
void fn_push(int num, Stack S);

int pop(Stack S);
bool isEmpty(Stack S);
void print_result(Stack S);

int main()
{
	int n, m;
	Stack PtrL1, PtrL2;
// 利用scanf的返回值,来实现循环条件,输入两个数,且不为零
	while(scanf("%d%d", &n, &m) == 2 && (n || m)){
		PtrL1 = read(n);
		PtrL2 = find_push(m, PtrL1);
		print_result(PtrL2);
	}
	return 0;
}

Stack read(int n)
{
	Stack PtrL;
	PtrL = (Stack)malloc(sizeof(struct SNode));
	PtrL ->next = NULL;
	int num;
	while(n--){
		scanf("%d", &num);
		push(num, PtrL);

	}
	return PtrL;
}
void push(int num, Stack S)
{
	Stack new_s;
	new_s = (Stack)malloc(sizeof(struct SNode));
	new_s ->data = num;
	new_s ->next = S ->next;
	S ->next = new_s;
}
bool isEmpty(Stack S)
{
	if(S ->next == NULL){
		return true;
	}else{
		return false;
	}
}
Stack find_push(int num, Stack S)
{
	int n_t;
	if(isEmpty(S)){
		free(S);
		return (read(num));
	}
	while(num--){
		scanf("%d", &n_t);
		fn_push(n_t, S);              
	}
	return S;
}
void fn_push(int num, Stack S)
{
	Stack f_s;
	bool flag = false;
	f_s = S;
	while(!isEmpty(f_s)){
		if(num >= f_s ->next ->data){
			if(flag == true){
				break;
			}
			push(num, f_s);
			flag = true;
		}else{
			f_s = f_s ->next;
		}
	}
	if(flag == false){
		push(num, f_s);
	}
	return ;
}
int pop(Stack S)
{
	Stack p_s;
	int top;
	if(isEmpty(S)){
		printf("error 1 exit!");
		return -1;
	}else{
		p_s = S ->next;
		S ->next = p_s ->next;
		top = p_s ->data;
		free(p_s);
		return top;
	}
}
void print_result(Stack S)
{
	int n;
	if (isEmpty(S))
		printf("^v^!!!, error, <error 2>");
	while(!isEmpty(S)){
		n = pop(S);
		printf("%d ", n);
	}
	printf("\n");
}

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值