21. Merge Two Sorted Lists
来源:互联网 发布:qq堂能不能再mac上运行 编辑:程序博客网 时间:2024/06/05 12:50
题目描述:
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
思路:
两链表不一定等长,先遍历比较两链表都不为空时的最小值存入新链表,当某一链表下一个值为空时,将另一链表剩余部分存入新链表
当前解决:
# Definition for singly-linked list.# class ListNode(object):# def __init__(self, x):# self.val = x# self.next = Noneclass Solution(object): def mergeTwoLists(self, l1, l2): l3 = ListNode(0) p = l3 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 l1: p.next = l1 else: p.next = l2 return l3.next
阅读全文