Skip to content

Instantly share code, notes, and snippets.

@Henryhehe
Created October 11, 2018 22:23
Show Gist options
  • Select an option

  • Save Henryhehe/c493af326779d2d50e19c86ebf9b3dfd to your computer and use it in GitHub Desktop.

Select an option

Save Henryhehe/c493af326779d2d50e19c86ebf9b3dfd to your computer and use it in GitHub Desktop.
List question set
#142 Linked List Cycle II
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return None
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
break
else:
return None
while head != slow:
slow = slow.next
head = head.next
return head
# Remove Linked List Elements:
class Solution:
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
if not head:
return None
dummy = ListNode(-1)
dummy.next = head
cur = dummy
while cur.next:
if cur.next.val == val:
cur.next = cur.next.next
else:
cur = cur.next
return dummy.next
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
# 382.Linked List Random Node
class Solution(object):
def __init__(self, head):
"""
@param head The linked list's head.
Note that the head is guaranteed to be not null, so it contains at least one node.
:type head: ListNode
"""
self.head = head
def getRandom(self):
"""
Returns a random node's value.
:rtype: int
"""
length = 0
head = self.head
while head:
length += 1
head = head.next
head = self.head
for _ in range(random.randrange(length)):
head = head.next
return head.val
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment