知识点:链表
难度:中等
题目描述:
输入两个链表,找出它们的第一个公共结点。(注意因为传入数据是链表,所以错误测试数据的提示是用其他方式显示的,保证传入数据是正确的)
思路:
如果两个链表有公共节点,那么公共节点出现在两个链表的尾部。如果从两个链表的尾部开始往前比较,那么最后一个相同的节点就是第一个公共结点。
单向链表只能从头节点开始按顺序遍历,最后才能到达尾节点。
所以需要利用两个列表辅助操作,具体操作如下:
- 分别把两个链表的节点放入到两个列表里,这样两个链表的尾节点就位于两个列表的尾元素,接下来比较两个列表的尾元素是否相同。
- 如果相同,则把列表的尾元素弹出接着比较下一个尾元素,直到找到最后一个相同的节点。
详解:
方法:(利用两个列表辅助)
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def FindFirstCommonNode(self, pHead1, pHead2):
# write code here
lst1=[]
lst2=[]
while pHead1:
lst1.append(pHead1)
pHead1=pHead1.next
while pHead2:
lst2.append(pHead2)
pHead2=pHead2.next
lst=None
while lst1 and lst2 and lst1[-1] == lst2[-1]:
lst=lst1.pop()
lst2.pop()
return lst
代码测试:
# -*- coding:utf-8 -*-
'''
输入两个链表,找出它们的第一个公共结点。
(注意因为传入数据是链表,所以错误测试数据的提示是用其他方式显示的,保证传入数据是正确的)
'''
'''
如果两个链表有公共节点,那么公共节点出现在两个链表的尾部。
如果从两个链表的尾部开始往前比较,那么最后一个相同的节点就是第一个公共结点。
'''
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def FindFirstCommonNode(self, pHead1, pHead2):
# write code here
#将两个链表的值分别存入到列表中
lst1=[]
lst2=[]
while pHead1:
lst1.append(pHead1.val)
pHead1=pHead1.next
#print(lst1)
while pHead2:
lst2.append(pHead2.val)
pHead2=pHead2.next
#print(lst2)
#对比两个列表中的最终元素是否相同
lst=None
while lst1 and lst2 and lst1[-1] == lst2[-1]:
lst=lst1.pop()
lst2.pop()
print(lst)
#print(type(lst))
node1=ListNode(1)
node2=ListNode(2)
node3=ListNode(6)
node4=ListNode(7)
node1.next=node2
node2.next=node3
node3.next=node4
nodeT1=ListNode(4)
nodeT2=ListNode(5)
nodeT3=ListNode(6)
nodeT4=ListNode(7)
nodeT1.next=nodeT2
nodeT2.next=nodeT3
nodeT3.next=nodeT4
s=Solution()
s.FindFirstCommonNode(node1,nodeT1)
运行结果: