2202: 合并链表(线性表)
Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 146 Solved: 81
[ Submit][ Status][ Web Board]
Description
(线性表)假设有两个按元素值递增次序排列的线性表,均以单链表形式存储。请编写算法将这两个单链表归并为一个按元素值递减次序排列的单链表,并要求利用原来两个单链表的结点存放归并后的单链表。
Input
输入长度n:5
输入数据:1 2 5 6 8
输入长度m:5
输入数据:3 4 7 9 10
Output
10 9 8 7 6 5 4 3 2 1
Sample Input
4
7 9 10 11
4
8 12 13 14
Sample Output
14 13 12 11 10 9 8 7
#include <stdio.h> #include <stdlib.h> #include<iostream> using namespace std; #define MaxSize 100 typedef int ElemType; typedef struct LNode { ElemType data; struct LNode *next; } LinkList; void CreatList(LinkList *&L) { LinkList *s,*r; int i,a[100],n; L=(LinkList *)malloc(sizeof(LinkList)); r=L; scanf("%d",&n); for(i=0; i<n; i++) { scanf("%d",&a[i]); s=(LinkList *)malloc(sizeof(LinkList)); s->data=a[i]; r->next=s; r=s; } r->next=NULL; } void UnionList(LinkList *L1,LinkList *L2,LinkList *&L) { LinkList *p1=L1->next,*p2=L2->next,*r,*s; L=(LinkList *)malloc(sizeof(LinkList)); r=L; while(p1!=NULL&&p2!=NULL) { if(p1->data<p2->data) { s=(LinkList *)malloc(sizeof(LinkList)); s->data=p1->data; r->next=s; r=s; p1=p1->next; } else { s=(LinkList *)malloc(sizeof(LinkList)); s->data=p2->data; r->next=s; r=s; p2=p2->next; } } while(p1!=NULL) { s=(LinkList *)malloc(sizeof(LinkList)); s->data=p1->data; r->next=s; r=s; p1=p1->next; } while(p2!=NULL) { s=(LinkList *)malloc(sizeof(LinkList)); s->data=p2->data; r->next=s; r=s; p2=p2->next; } r->next=NULL; } void sort(LinkList *&L) { LinkList *p,*pre,*q; p=L->next->next; L->next->next=NULL; while(p!=NULL) { q=p->next; pre=L; while(pre->next!=NULL&&pre->next->data>p->data) pre=pre->next; p->next=pre->next; pre->next=p; p=q; } } void DispList(LinkList *&L) { LinkList *p=L->next; while(p!=NULL) { printf("%d ",p->data); p=p->next; } } int main() { LinkList *L1,*L2,*L; CreatList(L1); CreatList(L2); UnionList(L1,L2,L); sort(L); DispList(L); return 0; }