1链式有序表的合并
关于数据结构的一个整理:
1、链式有序表的合并
2、栈
3、队列
4、二叉树、哈夫曼报文
5、图论
6、十大排序
7、校园导航系统
文章目录
- 链式有序表的合并
链式有序表的合并
#include <iostream>
using namespace std;typedef struct LNode { int data; LNode* next;
}LNode, * LinkList;void CreateList(LinkList& L, int n) { //尾插法创建链表L = new LNode;L->next = NULL;LinkList p;LinkList r = L;for (int i = 0; i < n; ++i) {p = new LNode;cin >> p->data;p->next = NULL;r->next = p;r = p;}cout << "创建成功" << endl;
}void MergeList(LinkList& A, LinkList& B, LinkList& C) {//已知单链表A、B的元素按值非递减排列LinkList pa, pb, pc;C = new LNode;C->next = NULL;pa = A->next; pb = B->next; //pa pb分别指向两个表的第一个结点C = A; //A的头节点作为C的头节点 pc = C; //pc指向C的头节点 while (pa && pb) { //当A B均未到末尾,取两表中较小的结点插入到C中if (pa->data <= pb->data) {pc->next = pa;pc = pa;pa = pa->next;}else {pc->next = pb;pc = pb;pb = pb->next;}}pc->next = pa ? pa : pb; //将非空的剩余段插入C中delete B;
}void ShowList(LinkList& L) { //输出链表LinkList p = L->next;while (p) {cout << p->data << " ";p = p->next;}cout << endl;
}void SortList(LinkList& L)
{LinkList p = L->next;LinkList pre, rear, cur;for (pre = p,cur=pre->next; cur != NULL; cur = cur->next) {cout << pre->data << endl;cout << cur->data << endl;system("pause");for (rear = p->next; rear != NULL; rear = rear->next) {if (pre->data < rear->data) {pre->next = rear;cur->next = rear->next;rear->next = cur;}}}}int main() {int m, n;LinkList A, B, C;cout << "创建表A,请输入插入元素个数:";cin >> m;cout << "请输入插入的元素:" << endl;CreateList(A, m);cout << "创建表B,请输入插入元素个数:";cin >> n;cout << "请输入插入的元素:" << endl;CreateList(B, n);MergeList(A, B, C);cout << "合并结果:" << endl;SortList(C);ShowList(C);return 0;
}