LeetCode21 Merge Two Sorted Lists

题意:

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. (Easy)

分析:

链表题,注意细节即可。

链表merge和数组merge的不同在于链表不用拷一份出来,倒腾一下指针就可以啦。

注意事项有:

1. dummy node用于输出,head(或者换个名字)用于遍历;

2. l1,l2是不是为空,一个结束遍历之后记得把另一个剩下的加上去。

代码:

 1 class Solution {
 2 public:
 3     ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
 4         if (l1 == nullptr) {
 5             return l2;
 6         }
 7         if (l2 == nullptr) {
 8             return l1;
 9         }
10         ListNode dummy(0);
11         ListNode* head = &dummy;
12         while (l1 != nullptr && l2 != nullptr) {
13             if (l1 -> val < l2 -> val) {
14                 head -> next = l1;
15                 head = head -> next;
16                 l1 = l1 -> next;
17             }
18             else {
19                 head -> next = l2;
20                 head = head -> next;
21                 l2 = l2 -> next;
22             }
23         }
24         if (l1 != nullptr) {
25             head -> next = l1;
26         }
27         if (l2 != nullptr) {
28             head -> next = l2;
29         }
30         return dummy.next;
31 
32     }
33 };

优化一下:

head = head -> next是不论if 还是else都要做的,拿出来写;

按本题的写法和ListNode的定义,其实开始不用判断l1,l2是否为空。(但一般来讲还是写上为好...)

代码:

 1 class Solution {
 2 public:
 3     ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
 4         ListNode dummy(0);
 5         ListNode* head = &dummy;
 6         while (l1 != nullptr && l2 != nullptr) {
 7             if (l1 -> val < l2 -> val) {
 8                 head -> next = l1;
 9                 l1 = l1 -> next;
10             }
11             else {
12                 head -> next = l2;
13                 l2 = l2 -> next;
14             }
15             head = head -> next;
16         }
17         if (l1 != nullptr) {
18             head -> next = l1;
19         }
20         if (l2 != nullptr) {
21             head -> next = l2;
22         }
23         return dummy.next;
24     }
25 };

 

今天七夕,算是半个假期,状态不是很好,水一道链表题练练手啦。明天开始重新步入正轨按照题号刷啦!!!

posted @ 2016-08-09 22:23  wangxiaobao1114  阅读(158)  评论(0编辑  收藏  举报