題目1519:合併兩個排序的鏈表


輸入: node

輸入可能包含多個測試樣例,輸入以EOF結束。
對於每一個測試案例,輸入的第一行爲兩個整數n和m(0<=n<=1000, 0<=m<=1000):n表明將要輸入的第一個鏈表的元素的個數,m表明將要輸入的第二個鏈表的元素的個數。
下面一行包括n個數t(1<=t<=1000000):表明鏈表一中的元素。接下來一行包含m個元素,s(1<=t<=1000000)。 ios

輸出:

對應每一個測試案例,
如有結果,輸出相應的鏈表。不然,輸出NULL。 測試

樣例輸入:
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* fHead = new Node;
			cin >> fHead->data;
			Node* node = NULL;
			Node* fP = fHead;
			for (int i = 1; i < n; i++) {
				node = new Node();
				cin >> node->data;
				fP->next = node;
				fP = node;
			}

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

			sP = sHead;
			fP = fHead;
			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;
}
相關文章
相關標籤/搜索