题目描述
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def EntryNodeOfLoop(self, pHead):
# write code here
templist = []
p = pHead
while p:
if p in templist:
return p
else:
templist.append(p)
p = p.next
题目描述
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
解题思路
自己写的代码太冗长,实在难看;牛客上找到的思路用Python实现的过程中,第一眼觉得挺简单;后来越看越觉得好像其中链表的运用有些溜,反复琢磨了好几遍,难道是晚上思路卡顿了?
def deleteDuplication(self, pHead):
first = ListNode(-1) #调用构造函数,创建一个对象
first.next = pHead
last = first #last是一个中间变量,起到工具的作用
while pHead and pHead.next:
if pHead.val == pHead.next.val:
val = pHead.val
while pHead and val==pHead.val:
pHead = pHead.next
last.next = pHead
else:
last = pHead
pHead = pHead.next
return first.next
包含测试版:
class Solution:
def deleteDuplication(self, pHead):
first = ListNode(-1) #初始化一个对象,-1是随便写的值,也可以是其他数字
first.next = pHead
last = first #last是一个中间变量,当工具用的
while pHead and pHead.next:
if pHead.val == pHead.next.val:
val = pHead.val
while pHead and val==pHead.val:
pHead = pHead.next
last.next = pHead
else:
last = pHead
pHead = pHead.next
return first.next
def getNewChart(self, list):
if list:
node = ListNode(list.pop(0))
node.next = self.getNewChart(list)
return node
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
if __name__ == '__main__':
list = [1,1,1,2,3,3,4]
listNode = Solution().getNewChart(list)
head = Solution().deleteDuplication(listNode)
while head:
print(head.val, end=" ")
head = head.next
题目描述
输入两个链表,找出它们的第一个公共结点。
# -*- 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
list1 = []
list2 = []
node1 = pHead1
node2 = pHead2
while node1:
list1.append(node1.val)
node1 = node1.next
while node2:
if node2.val in list1:
return node2
else:
node2 = node2.next