有两张非递增有序的线性表A,B,采用顺序存储结构,两张表合并用c表存,要求C为非递减有序的,然后删除C表中值相同的多余元素。元素类型为整型
输入格式:
第一行输入输入表A的各个元素,以-1结束,中间用空格分隔;第二行输入表B的各个元素,以-1结束,中间用空格分隔。
输出格式:
输出结果为表C的非递减有序序列,中间用英文逗号分隔
代码如下:
#include<iostream> #define MAX 1000 using namespace std; typedef struct { int* elem; int length; }SqList; SqList input(SqList& s) { s.elem = new int[MAX]; s.length = 0; int a, i = 0; cin >> a; while (a != -1) { if (i == 0) { s.elem[i] = a; cin >> a; i++; continue; } if (s.elem[i - 1] != a) { s.elem[i] = a; i++; } cin >> a; } s.length = i; return s; } void add(SqList& a, SqList& b, SqList& c) { if (a.length == 0 || b.length == 0) return; int i = a.length - 1, j = b.length - 1, k = 0; c.elem = new int[MAX]; c.length = 0; while (i >= 0 && j >= 0) { if (a.elem[i] == b.elem[j]) { c.elem[k] = a.elem[i]; i--; j--; k++; } else if (a.elem[i] < b.elem[j]) { c.elem[k] = a.elem[i]; i--; k++; } else { c.elem[k] = b.elem[j]; j--; k++; } } //A表剩余的元素; while (i >= 0) { c.elem[k] = a.elem[i]; i--; k++; } //B表剩余的元素; while (j >= 0) { c.elem[k] = b.elem[j]; j--; k++; } c.length = k; } void print(SqList& c) { cout << c.elem[0]; for (int i = 1; i < c.length; i++) { cout << "," << c.elem[i]; } } int main() { SqList A, B, C; A = input(A); B = input(B); add(A, B, C); print(C); return 0; }
标签:线性表,++,合并,elem,int,length,SqList,--,顺序存储
From: https://www.cnblogs.com/psh888/p/17001619.html