[LeetCode] 21. Merge Two Sorted Lists
题目链接:传送门
Description
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
Solution
题意:
合并两个有序序列
思路:
直接合并,太久没接触指针已是生疏,琢磨了老半天...
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode *head = NULL, **p = &head;
while (l1 != NULL || l2 != NULL) {
if (l2 == NULL || (l1 != NULL && l1->val < l2->val)) {
*p = l1;
l1 = l1->next;
} else {
*p = l2;
l2 = l2->next;
}
p = &((*p)->next);
}
return head;
}
};
补充:
在 Discuss 中有挺多写法可以借鉴的,也有递归的写法