## 最后一个元素输出之后,不允许有多余的一个空格存在;
通过判断栈内元素个数得知是否是最末的元素;另外此题是先递增排序---》逆序输出
同时可以采用‘头插法’输出
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include<stack>
using namespace std;
//结点
typedef struct Lnode {
int data;
struct Lnode *next;
}Lnode, *Linklist;
//尾插
void Creatlist(Linklist &L, int &e) {
Lnode *p = new Lnode;
p->data = e;
p->next = NULL; //处理新加入节点
Lnode *cur = L;
while (cur->next != NULL) {
cur = cur->next;
}
cur->next = p;
p->next = NULL;
}
//初始化
void Initlist(Linklist &L) {
L = new Lnode;
L->next = NULL;
}
//合并(非递减)
void Merge(Linklist &L1, Linklist &L2, Linklist &L) {
Lnode *c1 = L1->next;
Lnode *c2 = L2->next;
Lnode *p = L; //结果
while (c1&&c2) {
if (c1->data == c2->data) {
p->next = c1; //链接c1
p = p->next;
c1 = c1->next;
p->next = c2; //链接c2
p = p->next;
c2 = c2->next;
}
else if (c1->data > c2->data) {
p->next = c2;
p = p->next;
c2 = c2->next;
}
else {
p->next = c1;
c1 = c1->next;
p = p->next;
}
}
while (c1) {
p->next = c1;
c1 = c1->next;
p = p->next;
}
while (c2) {
p->next = c2;
c2 = c2->next;
p = p->next;
}
}
//打印
void Print(Linklist &L) {
Lnode *cur = L->next;
while (cur->next != NULL) {
cout << cur->data << " ";
cur = cur->next;
}
cout << cur->data << endl;
}
int main() {
int n, m;
while (scanf("%d %d",&n,&m)!=EOF) {
if (n == 0 && m == 0) break;
Linklist L1; Linklist L2; Linklist L; //结果
Initlist(L1); Initlist(L2); Initlist(L);
for (int i = 0; i < n; i++) { //建L1
int e;
cin >> e;
Creatlist(L1, e);
}
for (int i = 0; i < m; i++) { //建L2
int e;
cin >> e;
Creatlist(L2, e);
}
Merge(L1, L2, L);//合并
//逆序
stack <int> mystack;//逆序存放
Lnode *cur = L->next;//第一个节点
while (cur) //入栈
{
mystack.push(cur->data);
cur = cur->next;
}
while (!mystack.empty()) { //逆序输出
if(mystack.size()>1){
printf("%d ", mystack.top());
mystack.pop();
}
else {
cout << mystack.top()<<endl;
mystack.pop();
}
}
}
}
BJFU 226基于链表的两个非递减有序序列的合并
最新推荐文章于 2023-10-29 22:27:44 发布