比较顺序表A和B的大小

题目:设A=(a1, a2, ... ,am)和B=(b1, b2, ... ,bn) 均为顺序表,A' 和B' 分别是除去最大公共前缀后的子表。如A= ('b', 'e', 'i', 'j', 'i', 'n', 'g'), B= ('b', 'e', 'i', 'f', 'a', 'n', 'g'), 则两者的最大公共前缀为'b', 'e', 'i', 在两个顺序表中除去最大公共前缀后的子表分别为A' =('j', 'i', 'n', 'g'), B' = ('f', 'a', 'n', 'g')。若A' = B' = 空表,则A = B; 若A' = 空表且B' ≠ 空表,或两者均不空且A'的第一个元素值小于B'的第一个元素的值,则A<B;否则A>B。编写一个算法,根据上述方法比较A和B的大小。

代码实现:

#include <iostream>
#include <cstdlib>
#define N 40001
using namespace std; 

typedef int DataType;
typedef struct node1{
	DataType a[N];
	DataType lenth;
}LineList_1;
typedef struct node2{
	DataType a[N];
	DataType lenth;
}LineList_2;

void Init_List(LineList_1& L1, LineList_2& L2){
	L1.lenth = 0;
	L2.lenth = 0;
}

void Create_List(LineList_1& L1, LineList_2& L2){
	int n;
	cout << "请输入第一个要输入的序列个数:";
	cin >> n;
	cout << "请输入" << n << "个数字:";
	for (int i = 0; i < n; i++){
		cin >> L1.a[i]; 
	} 
	L1.lenth = n;
	
	cout << "请输入第二个要输入的序列个数:";
	cin >> n;
	cout << "请输入" << n << "个数字:";
	for (int i = 0; i < n; i++){
		cin >> L2.a[i]; 
	} 
	L2.lenth = n;
}

int cmp(int a[], int a_len, int b[], int b_len){
	// 优先比较值再比较长度 
	int min_len = a_len < b_len ? a_len : b_len;
	for (int i = 0; i < min_len; i++)
		if (a[i] != b[i]) return a[i] > b[i];
	if (a_len != b_len) return a_len > b_len;
	return -1;
}

int Deal(LineList_1& L1, LineList_2& L2){
	int a_1[L1.lenth], a_2[L2.lenth];
	int a_1_lenth = 0, a_2_lenth = 0;
	int min_len = L1.lenth < L2.lenth ? L1.lenth : L2.lenth;
	
	// 去除公共前缀 
	for (int i = 0; i <= min_len; i++){
		if (L1.a[i] != L2.a[i]){
			a_1[a_1_lenth++] = L1.a[i];
			a_2[a_2_lenth++] = L2.a[i]; 
		}
	}
	if (L1.lenth > L2.lenth)
		while (a_1_lenth < L1.lenth)
			a_1[a_1_lenth] = L1.a[a_1_lenth], a_1_lenth++;
			 
	return cmp(a_1, a_1_lenth, a_2, a_2_lenth);
}

int main(){
	LineList_1 L1;
	LineList_2 L2;
	// 初始化序列 
	Init_List(L1, L2);
	// 创建序列 
	Create_List(L1, L2);
	
	//处理序列 
	if (Deal(L1, L2) == 1) cout << "A>B";
	else if(Deal(L1, L2) == -1) cout << "A=B";
	else cout << "A<B";
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

萌新在此~~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值