版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
问题描述:将两个有序表合并。例如 l1={1,2,3,4,5},l2={2,3,4,5,6} =>l3={1,2,2,3,3,4,4,5,5,6}。
分析:将两个有序表合并,就是归并的过程。
解题思路:实现归并排序的归并过程即可。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct List {
int data;
struct List* next;
};
typedef List* ListPtr;
void
create_list(ListPtr* list_node, int data) {
ListPtr refer_ptr = (ListPtr)malloc(sizeof(struct List));
refer_ptr->data = data;
refer_ptr->next = NULL;
*list_node = refer_ptr;
}
void
insert_node(ListPtr* list_node, struct List* node) {
struct List** refer_ptr = list_node;
while (*refer_ptr)
refer_ptr = &(*refer_ptr)->next;
*refer_ptr = node;
node->next = NULL;
}
void
sort_list_node(ListPtr l1, ListPtr l2, ListPtr* l3) {
if (l1 == NULL || l2 == NULL)
return;
struct List** refer_l3_ptr = l3;
while (l1 && l2) {
if (l1->data < l2->data) {
*refer_l3_ptr = l1;
l1 = l1->next;
refer_l3_ptr = &(*refer_l3_ptr)->next;
}
else {
*refer_l3_ptr = l2;
l2 = l2->next;
refer_l3_ptr = &(*refer_l3_ptr)->next;
}
}
while (l1) {
*refer_l3_ptr = l1;
l1 = l1->next;
refer_l3_ptr = &(*refer_l3_ptr)->next;
}
while (l2) {
*refer_l3_ptr = l2;
l2 = l2->next;
refer_l3_ptr = &(*refer_l3_ptr)->next;
}
}
void
print_list(ListPtr* list) {
struct List** refer_ptr = list;
while (*refer_ptr) {
cout << (*refer_ptr)->data << " ";
refer_ptr = &(*refer_ptr)->next;
}
cout << endl;
}
int main(int argc, char** argv) {
struct List* l1 = NULL;
struct List* l2 = NULL;
int data = 0;
cin >> data;
create_list(&l1, data);
while (getchar() == ' ') {
cin >> data;
struct List* node = (struct List*)malloc(sizeof(struct List));
node->data = data;
insert_node(&l1, node);
}
cin >> data;
create_list(&l2, data);
while (getchar() == ' ') {
cin >> data;
struct List* node = (struct List*)malloc(sizeof(struct List));
node->data = data;
insert_node(&l2, node);
}
struct List* l3 = NULL;
sort_list_node(l1, l2, &l3);
print_list(&l3);
system("pause");
return 0;
}