# 题目1519：合并两个排序的链表

2014/04/04 11:23

``````5 2
1 3 5 7 9
2 4
0 0``````

``````1 2 3 4 5 7 9
NULL``````
``````#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;

Node(int data) {
this->data = data;
this->next = NULL;
}

Node() {
this->data = 0;
this->next = NULL;
}
};
int main() {

int n, m;
while (cin >> n >> m) {
if(n==0 && m == 0){
cout<<"NULL"<<endl;
}else{

Node* node = NULL;
for (int i = 1; i < n; i++) {
node = new Node();
cin >> node->data;
fP->next = node;
fP = node;
}

for (int i = 1; i < m; i++) {
node = new Node;
cin >> node->data;
sP->next = node;
sP = node;
}

Node* fPost = NULL;
Node* sPost = NULL;

Node* result = new Node;
Node* rP = result;
while (fP && sP) {
fPost = fP->next;
sPost = sP->next;

if (fP->data <= sP->data) {
fP->next = NULL;
rP->next = fP;
rP = fP;
fP = fPost;
} else {
sP->next = NULL;
rP->next = sP;
rP = sP;
sP = sPost;
}
}

if (fP) {
rP->next = fP;
}
if (sP) {
rP->next = sP;
}

rP = result->next;
for (int i = 0; i < (m + n - 1); i++) {
cout << rP->data << " ";
rP = rP->next;
}
cout << rP->data << endl;
}
}
return 0;
}``````

0
2 收藏

0 评论
2 收藏
0