(ps:我不明白为什么easy题的阅读量会比较高。。。。

题目:

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

思路:

又是数据结构课本题。。l1和l2头部比较,取较小者放置res,并后移。最后把剩下的一个链接上

代码:

 ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
	 if (!l1) return l2;
	 if (!l2) return l1;
	 if (l1->val > l2->val)
		 swap(l1, l2);
	 ListNode *res = l1, *r = l1;
	 l1 = l1->next;
	 while (l1&&l2) {
		 if (l1->val > l2->val) {
			 res->next = l2;
			 l2 = l2->next;
		 }
		 else {
			 res->next = l1;
			 l1 = l1->next;
		 }
		 res = res->next;
	 }
	 if (l1)
		 res->next = l1;
	 else
		 res->next = l2;
	 return r;
 }