构造两个带有表头结点的有序单链表La、Lb,编写程序实现将Lb融合到La中。 融合的思想是:依次将Lb的每一个结点按数值大小插入到La中。
输入数据为两行有序数据,分别有5个数据。建立两个链表并将每行数据存入链表结点的数据域。
输出为一行10个数据,每个数据之间有一个空格。要求在融合数据后再遍历链表La,输出其数据域的值。
#include <iostream>
#include <cmath>
#include <string>
#include <string.h>
#include <iomanip>
#include <fstream>
using namespace std;
struct node {
int data;
node *next;
};
struct list {
node *head;
int len;
};
void begin(list &a, int n) {
node *ptr = new node;
ptr->data = n;
ptr->next = NULL;
if (a.head == NULL) {
a.head = ptr;
a.len = 1;
} else {
node *pt = a.head;
while (pt->next != NULL) {
pt = pt->next;
}
pt->next = ptr;
a.len++;
}
delete ptr;
}
void sort(list &a, list &b) {
node *pt = b.head;
node *ptr = a.head;
while (pt) {
node *ptr = a.head;
if ((pt->data) < (ptr->data) ) {
node *temp = pt;
temp->next = ptr;
a.head = temp;
pt = pt->next;
continue;
}
while (pt->data > ptr->data) {
ptr = ptr->next;
}
node *temp = pt;
temp->next = ptr->next;
ptr->next = temp;
pt = pt->next;
}
}
void show(list &a) {
node *ptr = new node;
ptr = a.head;
for (int j = 0; j < 10; j++) {
cout << ptr->data << " ";
ptr = ptr->next;
}
delete ptr;
}
int main() {
int i = 0, n = 0;
list a, b;
a.head = NULL;
a.len = 0;
for (i = 0; i < 5; i++) {
cin >> n;
begin(a, n);
}
b.head = NULL;
b.len = 0;
for (i = 0; i < 5; i++) {
int n = 0;
cin >> n;
begin(b, n);
}
show(a);
return 0;
}