顺序表应用5:有序顺序表归并SDUTOJ3329

mac2022-06-30  34

顺序表应用5:有序顺序表归并

Time Limit: 100 ms Memory Limit: 880 KiB

Submit Statistic

Problem Description

已知顺序表A与B是两个有序的顺序表,其中存放的数据元素皆为普通整型,将A与B表归并为C表,要求C表包含了A、B表里所有元素,并且C表仍然保持有序。

Input

 输入分为三行: 第一行输入m、n(1<=m,n<=10000)的值,即为表A、B的元素个数; 第二行输入m个有序的整数,即为表A的每一个元素; 第三行输入n个有序的整数,即为表B的每一个元素;

Output

 输出为一行,即将表A、B合并为表C后,依次输出表C所存放的元素。

Sample Input

5 3 1 3 5 6 9 2 4 10

Sample Output

1 2 3 4 5 6 9 10 #include <stdio.h> #include <stdlib.h> #include <string.h> struct node { int data; struct node *next; }; struct node * Creat_LinkList(int); struct node * Merge(struct node *, struct node *); void Output(struct node *); int main() { int m, n; struct node *head1, *head2; scanf("%d %d", &m, &n); head1 = Creat_LinkList(m); head2 = Creat_LinkList(n); head1 = Merge(head1, head2); Output(head1); return 0; } struct node * Creat_LinkList(int n) { struct node *head, *p, *tail; head = (struct node *)malloc(sizeof(struct node)); head->next = NULL; tail = head; while(n--) { p = (struct node *)malloc(sizeof(struct node)); scanf("%d", &p->data); p->next = tail->next; tail->next = p; tail = p; } tail->next = NULL; return head; }; struct node *Merge(struct node *head1, struct node *head2) { struct node *p1, *p2, *tail; p1 = head1->next; p2 = head2->next; tail = head1; tail->next = NULL; free(head2); while(p1 && p2) { if(p1->data < p2->data) { tail->next = p1; p1 = p1->next; tail = tail->next; tail->next = NULL; } else { tail->next = p2; p2 = p2->next; tail = tail->next; tail->next = NULL; } } if(p1 != NULL) tail->next = p1;///此处如果p1不为空,则将p1后面的直接连上去 else tail->next = p2; return head1; }; void Output(struct node *head) { struct node *p; p = head->next; while(p) { if(p == head->next) printf("%d", p->data); else printf(" %d", p->data); p = p->next; } printf("\n"); }

 

最新回复(0)