#思路1:先顺序遍历第一个链表的结点,每遍历到一个结点时候,在第二个链表上顺序遍历每个结点。如果在第二个链表上有和第一个链表相同的结点,则找到了公共结点。复杂度O(mn)
#思路2:使用辅助栈,分别把两个链表放入到两个栈中,这样两个链表的尾结点就位于两个栈的栈顶,在比较栈顶元素是否相同。如果相同则弹出栈顶元素,接着比较下一个栈顶,直到找到最后一个相同的结点。定义了辅助栈用空间来换取时间。复杂度O(m+n)
class ListNode(object):
def __init__(self,x):
self.val=x
self.next=None
node1 = ListNode(1)
node1.next = ListNode(2)
node1.next.next = ListNode(3)
node1.next.next.next = ListNode(4)
node1.next.next.next.next = ListNode(5)
node2 = ListNode(8)
node2.next = ListNode(6)
node2.next.next = ListNode(4)
node2.next.next.next = ListNode(5)
def findFirstCommentNode(pHead1, pHead2):
stack1 = []
stack2 = []
while pHead1:
stack1.append(pHead1)
pHead1 = pHead1.next
while pHead2:
stack2.append(pHead2)
pHead2 = pHead2.next
first_commentNode = None
while stack1 and stack2 and stack1[-1].val == stack2[-1].val:
first_commentNode = stack1.pop()
stack2.pop()
return first_commentNode
# print('第一个公共结点',findFirstCommentNode(node1,node2).val)
#思路3:先遍历两个链表,得到链表的长度以及长的链表比短的链表多几个结点,接着第二次遍历的时候,在较长的链表上先走多的结点数,接着在同时遍历两个链表,找到第一个相同结点就是他们的公共结点。这样不需要空间复杂度O(m+n)
def getListLength(pHead):
length = 0
while pHead:
length+=1
pHead = pHead.next
return length
def findFirstCommentNode2(pHead1, pHead2):
length1 = getListLength(node1)
length2 = getListLength(node2)
len_diff = abs(length1-length2)
longHead = pHead1
shortHead = pHead2
if length1 < length2:
longHead = pHead2
shortHead = pHead1
#先在长链表上走几步,在同时遍历两个链表
for i in range(len_diff):
longHead = longHead.next
while shortHead and longHead and shortHead.val != longHead.val:
shortHead = shortHead.next
longHead = longHead.next
return shortHead
# print(findFirstCommentNode2(node1,node2).val)
两个链表的第一个公共结点--python
最新推荐文章于 2022-02-16 00:16:15 发布