Day41 找到有环链表的入口点

2020-07-05  本文已影响0人  快乐的老周

给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。

为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。

说明:不允许修改给定的链表。

示例 1:

输入:head = [3,2,0,-4], pos = 1

输出:tail connects to node index 1

解释:链表中有一个环,其尾部连接到第二个节点。

示例 2:

输入:head = [1,2], pos = 0

输出:tail connects to node index 0

解释:链表中有一个环,其尾部连接到第一个节点。

示例 3:

输入:head = [1], pos = -1

输出:no cycle

解释:链表中没有环。

来源:力扣(LeetCode)

链接:力扣 https://leetcode-cn.com/problems/linked-list-cycle-ii

class Solution():
def hasCycle_hash(self, head): # hash
s = set()
tmp = head
while tmp:
if tmp in s:
return True
else:
s.add(tmp)
tmp = tmp.next
return False

def hasCycle_fast_slow_point(self, head): #快慢指针
    #没有考虑链表长度小于2的情况
    slow = fast = head
    while slow != None and fast != None:
        slow = slow.next
        fast = fast.next.next
        if slow == fast:
            return True
    return False

def find_Dup_entry(self, head):
    slow = fast = head
    while slow != None and fast != None:
        slow = slow.next
        fast = fast.next.next
        if slow == fast:
            slow = head
            while slow != fast:
                slow = slow.next
                fast = fast.next
            return slow.val

class Node():
def init(self, val):
self.val = val
self.next = None

class SingleLinkList():
def init(self):
self.head = None

def is_empty(self):
  if self.head == None:
      return True

def length(self):
  cur = self.head
  count = 0
  while cur != None:
      cur = cur.next
      count +=1
  return count

def travel(self):
  cur = self.head
  while cur != None:
      print(cur.val, end=' ')
      cur = cur.next
  print('\n')

def append(self, item):
  node = Node(item)
  cur = self.head
  if self.is_empty():
      self.head = node
  else:
      while cur.next != None:
          cur = cur.next
      cur.next = node

def reverseList(self):
  # if self.head == None or self.head.next == None:
      # return self.head
  pre = None
  cur = self.head
  while cur != None:
      next = cur.next
      cur.next = pre
      pre = cur
      cur = next
  self.head = pre

def addCycle(self, pos):
    count = 0
    cur = self.head
    prev = self.head
    end = self.head
    while end.next != None:
        if count != pos:
            cur = cur.next
            count += 1
        end = end.next
    end.next = cur

if name == 'main':
sll = SingleLinkList()
for i in range(1,11):
sll.append(i)
sll.travel()
sll.reverseList()
sll.travel()
sll.addCycle(3)

sll.travel() 不能运行,会死循环的

s = Solution()
print(f'Has cycle?(Hash): {s.hasCycle_hash(sll.head)}')
print(f'Has cycle?(Slow Fast point): {s.hasCycle_fast_slow_point(sll.head)}')
print('_' * 40)
print(f'Duplicate Entry value is: {s.find_Dup_entry(sll.head)}')

上一篇下一篇

猜你喜欢

热点阅读