【leetcode】【单链表】【21】Merge Two Sorted Lists

#include<iostream>
using namespace std;

struct ListNode {
	int val;
	ListNode *next;
	ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
	ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
		if (l1 == NULL){ //l1空
			return l2;
		}else if (l2 == NULL){ //l2空
			return l1;
		}else{ //都不空
			ListNode* cur1 = l1;
			ListNode* cur2 = l2;
			ListNode* preCur1 = NULL;
			if (cur1->val > cur2->val){
				ListNode* temp = cur2;
				cur2 = cur2->next;
				temp->next = cur1;
				l1 = preCur1 = temp;
			}else{
				preCur1 = cur1;
				cur1 = cur1->next;
			}
			while (cur1&&cur2){
				if (cur1->val > cur2->val){
					ListNode* temp = cur2;
					cur2 = cur2->next;
					temp->next = cur1;
					preCur1->next = temp;
					preCur1 = temp;
				}else{
					preCur1 = cur1;
					cur1 = cur1->next;
				}
			}
			if (cur2)
				preCur1->next = cur2;
			return l1;
		}	
	}
	ListNode* createList(ListNode* head){
		int numOfNode;
		int value;
		cout << "please input number of listNode:";
		cin >> numOfNode;
		cin >> value;
		head = new ListNode(value);
		ListNode* cur = head;
		for (int i = 1; i < numOfNode; ++i){
			cin >> value;
			ListNode* temp = new ListNode(value);
			cur->next = temp;
			cur = temp;
		}
		return head;
	}
	void printNode(ListNode* head){
		ListNode* cur = head;
		while (cur){
			cout << cur->val << " ";
			cur = cur->next;
		}
		cout << endl;
	}
};

int main(){
	Solution solution;

	ListNode* l1 = NULL;
	l1 = solution.createList(l1);
	solution.printNode(l1);

	ListNode* l2 = NULL;
	l2 = solution.createList(l2);
	solution.printNode(l2);

	l1 = solution.mergeTwoLists(l1, l2);
	solution.printNode(l1);

	system("pause");
	return 0;
}

原文地址:https://www.cnblogs.com/ruan875417/p/4558312.html