您的位置:首页 > 编程语言 > C语言/C++

leetcode21题 题解 翻译 C语言版 Python版

2016-04-14 19:49 681 查看
21. 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.

21.合并两个有序链表

合并两个有序链表并将其作为一个新链表返回。新链表应当由原来的两个链表的结点拼接而成。

思路:两个链表上分别设立游标来遍历,同时设立一个表示合并后链表的游标,不停地判断当前两链表的结点值,取小的结点将其拼接在合并后的链表上。由于链表都没有头结点,所以最开始要单独判断一下来获取最后合并链表的头结点。

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     struct ListNode *next;
* };
*/
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
if (!l1 && !l2) return NULL;
if (!l1) return l2;
if (!l2) return l1;
struct ListNode *head, *p;
if (l1->val < l2->val){
head = p = l1;
l1 = l1->next;
}
else {
head = p = l2;
l2 = l2->next;
}
while (l1 && l2){
if (l1->val < l2->val){
p->next = l1;
l1 = l1->next;
}
else {
p->next = l2;
l2 = l2->next;
}
p = p->next;
}
if (!l1){
p->next = l2;
}
if (!l2){
p->next = l1;
}
return head;
}


# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if not (l1 or l2): return None
if not l1: return l2
if not l2: return l1
head, p = None, None
if (l1.val < l2.val):
head, p = l1, l1
l1 = l1.next
else:
head, p = l2, l2
l2 = l2.next
while l1 and l2:
if l1.val < l2.val:
p.next = l1
l1 = l1.next
else:
p.next = l2
l2 = l2.next
p = p.next
if not l1:
p.next = l2
if not l2:
p.next = l1
return head
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: