链表合并
来源:互联网 发布:淘宝卖家真实现状 编辑:程序博客网 时间:2024/06/03 20:25
http://ask.csdn.net/questions/676058#原题目
#include<iostream>using namespace std;typedef struct Node * List;struct Node {int Data;List Next;};List Read(int N){List L = new struct Node;L->Next = NULL;List LL = L;while (N--){List tmp = new struct Node;cin >> tmp->Data;cin.get();tmp->Next = NULL;LL->Next = tmp;LL = tmp;}List p;p = L;L = L->Next;delete p;return L;}List Attach(List L1, List L2)//长的在前面,短的插进去{List p1, p2;p1 = L1;p2 = L2;while (p2){p1 = L1;int k = p2->Data;if (k < p1->Data){List tmp = new struct Node;tmp->Data = k;tmp->Next = p1;L1=p1=tmp;}else{while (p1->Next){if (k > p1->Data&&k < p1->Next->Data)break;elsep1 = p1->Next;}if (!p1->Next){List tmp = new struct Node;tmp->Data = k;tmp->Next = NULL;p1->Next = tmp;}List tmp = new struct Node;tmp->Data = k;tmp->Next = p1->Next;p1->Next = tmp;}p2 = p2->Next;}return L1;}void Print(List L){List p = L;while (p){cout << p->Data << " ";p = p->Next;}}int main(){int N1,N2;cin >> N1;cin.get();List L1 = Read(N1);cin >> N2;cin.get();List L2 = Read(N2);List L;if(N1>N2)L=Attach(L1, L2);elseL = Attach(L2, L1);Print(L);cin.get();return 0;}
阅读全文