题目
【相交链表】五种解法~
给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null 。
题解
- 暴力解法。时间复杂度:O(n^2)。
- 哈希表。挨个节点放到哈希表中,然后是查哈希表。
- 栈。因为从后面开始是一样的,都放到栈中,弹出做比,什么时候不一样了就检索到了。
- 计算长度。
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
s1, s2 = 0, 0
p, q = headA, headB
# 计算长度
while p:
p = p.next
s1 += 1
while q:
q = q.next
s2 += 1
# 长链表先走,但不确定AB谁长,所以有两个循环,但实际上有至少一个循环不会执行
p, q = headA, headB
for i in range(s1 - s2):
p = p.next
for i in range(s2 - s1):
q = q.next
while p and q and p != q:
p = p.next
q = q.next
return p
作者:Meteordream
链接:https://leetcode.cn/problems/intersection-of-two-linked-lists/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
解题
自己写的是真丑啊……
# 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
"""
countA = 1
countB = 1
A = headA
B = headB
while A.next != None:
A = A.next
countA+=1
while B.next != None:
B = B.next
countB+=1
if A != B:
return None
A = headA
B = headB
if countB>countA:
for i in range(countB-countA):
B = B.next
while B != A:
B = B.next
A = A.next
return A
else:
for i in range(countA-countB):
A = A.next
while B != A:
B = B.next
A = A.next
return A
- 在一个用例卡住了:
1
[1]
[1]
0
0
没有考虑清楚边界情况。
问题
- 多个值同一个表达式赋值的习惯没有养成。更简洁。
- range内可以为负数,直接跳过此循环。