21. Merge Two Sorted Lists - easy
题目描述
合并两个有序链表
例子
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
解法
法1 - 非递归,逐次比较
法2 - 递归
解法1
非递归
# 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
"""
dummy = ListNode(-1)
p = dummy
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
p.next = l1 or l2
return dummy.next
解法2
递归
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if not l1:
return l2
if not l2:
return l1
if l1.val < l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
else:
l2.next = self.mergeTwoLists(l1, l2.next)
return l2
160. Intersection of Two Linked Lists - easy
题目描述
找到两个链表的交点入口
例子
A: a1 → a2
↘
c1 → c2 → c3
↗
B: b1 → b2 → b3
解法
1) 可以从尾部遍历链表就好了(当然不可能)
2) 知道两个链表的长度差,长链表的先走几步就好了
我们可以用两个指针分别遍历两个链表,当其中一个为空时,令其指向另一个链表的头部(类似长度差)
解法
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
p1 = headA
p2 = headB
while p1 != p2:
if p1:
p1 = p1.next
else:
p1 = headB
if p2:
p2 = p2.next
else:
p2 = headA
return p1