Leetcode 160题 Intersection of Two Linked Lists
Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
begin to intersect at node c1.
题目大意: 两条相交数组,返回相交点。
思路一:
两条数组若相交,从相交点往后必定相等。把两条数组存到栈中,把栈中相同的元素从栈底弹出,弹到元素不同为止。 不同则返回当前元素值,一直相同则返回None.
上代码。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
stack1 = []
stack2 = []
while headA: #数组存入栈的操作
stack1.append(headA)
headA = headA.next
while headB:
stack2.append(headB)
headB = headB.next
result = None
while stack1 and stack2: #当两个栈存在时
node1 = stack1.pop() #从栈底弹出元素。
node2 = stack2.pop()
if node1 != node2: #若弹出的元素不同
return result #返回None
else:
result = node1 #若相同,返回元素节点。
return result
本来考虑反转列表之后,用指针从第一个开始遍历,遍历到第一个不同的地方,返回这个地方的上一个值。 可是发现不能改变列表结构,那就算了。
2020/03/24
疫情中的英国。
加油!