1006: 单向链表(3)
Description
1、 请在LinkSortList类的基础上添加成员函数Merge,实现将两个有序表A,B的合并为表C,C中序列仍有序。要求利用A,B中的结点进行合并,合并后A,B置为空表。main代码已知,请勿改动。
//有序表类
template <class T>
class LinkSortList
{
public:
LinkSortList( ); //建立只有头结点的空链表
~LinkSortList(); //析构函数
void Insert(T x); //sort insert
int Length();
void DispList( ); //遍历单链表,按序号依次输出各元素
void Merge(LinkSortList<T> &A, LinkSortList<T> &B); //合并A,B到当前类
private:
Node<T> *first; //单链表的头指针
};
int main( ){
LinkSortList <int> A,B,C;
int x;
while(1){
cin>>x;
if(!x) break;
A.Insert(x);
}
while(1){
cin>>x;
if(!x) break;
B.Insert(x);
}
A.DispList();
B.DispList();
C.Merge(A,B);
C.DispList();
A.DispList();
B.DispList();
return 0;
}
Input
Output
Sample Input
342 4521 521 4 21 3 4 21 4 0
234 5 3 25 5236 34 65 23 34 0
Sample Output
The length:9
The elements:3 4 4 4 21 21 342 521 4521
The length:9
The elements:3 5 23 25 34 34 65 234 5236
The length:18
The elements:3 3 4 4 4 5 21 21 23 25 34 34 65 234 342 521 4521 5236
The length:0
The elements:
The length:0
The elements:
//
// Created by Legends丶Hu on 2020/2/3.
//
#include <iostream>
using namespace std;
template <class T>
struct Node{
T data;
Node<T> *next;
};
template<class T>
class LinkSortList {
public:
LinkSortList(); //建立只有头结点的空链表
~LinkSortList(); //析构函数
void Insert(T x); //sort insert
int Length();
void DispList(); //遍历单链表,按序号依次输出各元素
void Merge(LinkSortList<T> &A, LinkSortList<T> &B); //合并A,B到当前类
private:
Node <T> *first; //单链表的头指针
};
template<class T>
LinkSortList<T>::LinkSortList() {
first = new Node<T>;
first->next = NULL;
}
template<class T>
LinkSortList<T>::~LinkSortList() {
while (first) {
Node<T> *p = first;
first = first->next;
delete p;
}
}
template<class T>
void LinkSortList<T>::Insert(T x) {
Node<T> *p = first;
while (p->next) {
if(p->next->data > x)break;
p = p->next;
}
Node<T> *s = new Node<T>;
s->data = x;
s->next = p->next;
p->next = s;
}
template<class T>
int LinkSortList<T>::Length() {
int i = 0;
Node<T> *p = first->next;
while (p) {
p = p->next;
i++;
}
return i;
}
template<class T>
void LinkSortList<T>::DispList() {
Node<T> *p = first->next;
cout << "The length:" << Length() << endl;
cout << "The elements:";
while (p) {
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
template<class T>
void LinkSortList<T>::Merge(LinkSortList<T> &A, LinkSortList<T> &B) {
Node<T> *pa = A.first->next;
Node<T> *pb = B.first->next;
Node<T> *pc = first;
while(pa && pb) {
if(pa->data < pb->data){
pc->next = pa;
pc = pa;
pa = pa->next;
} else {
pc->next = pb;
pc = pb;
pb = pb->next;
}
}
if(pa)
pc->next = pa;
if(pb)
pc->next = pb;
A.first->next = NULL;
B.first->next = NULL;
}
int main() {
LinkSortList<int> A, B, C;
int x;
while (1) {
cin >> x;
if (!x) break;
A.Insert(x);
}
while (1) {
cin >> x;
if (!x) break;
B.Insert(x);
}
A.DispList();
B.DispList();
C.Merge(A, B);
C.DispList();
A.DispList();
B.DispList();
return 0;
}