标签:leetcode
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.
合并两个链表,考察的是指针操作。多注意指针是否为空,指针操作需谨慎。有两种情况:
1.其中一个链表为空,则直接返回另一个链表。
2.合并过程中,一个链表已经走到了末尾,即移动到了空指针,但另一个链表还剩下一段,则把剩下的这段接到合并后列表的最后
剩下都就是合并过程中的指针的值的比较而已。
C++:
/**
* 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) {
/* 有一个为空,合并后为非空的另一个链表 */
if(l1 == NULL)
return l2;
if(l2 == NULL)
return l1;
ListNode *head = NULL, *cur = NULL;
/* 初始化头指针 */
if(l1->val < l2->val)
{
head = l1;
l1 = l1->next;
}
else
{
head = l2;
l2 = l2->next;
}
/* 当前指针 */
cur = head;
/* 要两个链表都非空才可以一直往后合并 */
while(l1 && l2)
{
if(l1->val < l2->val)
{
cur->next = l1;
cur = cur->next;
l1 = l1->next;
}
else
{
cur->next = l2;
cur = cur->next;
l2 = l2->next;
}
}
/* 其中一个为空之后,把另一个非空的链表接到合并后链表的最后 */
if(l1) cur->next = l1;
else if(l2) cur->next = l2;
return head;
}
}; Python:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param two ListNodes
# @return a ListNode
def mergeTwoLists(self, l1, l2):
if not l1:
return l2
if not l2:
return l1
if l1.val < l2.val:
head = l1
l1 = l1.next
else:
head = l2
l2 = l2.next
cur = head
while l1 and l2:
if l1.val < l2.val:
cur.next = l1
l1 = l1.next
else:
cur.next = l2
l2 = l2.next
cur = cur.next
if l1:
cur.next = l1
elif l2:
cur.next = l2
return head【LeetCode】Merge Two Sorted Lists
标签:leetcode
原文地址:http://blog.csdn.net/jcjc918/article/details/44087437