1. 程式人生 > >21 Merge Two Sorted Lists

21 Merge Two Sorted Lists

水題

class Solution {
public:
	ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
		if (l1 == NULL&&l2 == NULL)return l1;
		ListNode *firstNode = new ListNode(0);
		ListNode *p = new ListNode(0);
		firstNode->next = p;
		while (l1 && l2) {
			if (l1->val < l2->val)
{ p->next = new ListNode(l1->val); p = p->next; l1 = l1->next; } else { p->next = new ListNode(l2->val); p = p->next; l2 = l2->next; } } if (l1)p->next = l1; else p->next = l2; firstNode = firstNode->next->next; return firstNode;
} };