题目1
题解1
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reorderList(self, head: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
"""
if not head: return None
p = head
stack = []
# 把所有节点压入栈中
while p:
stack.append(p)
p = p.next
# 长度
n = len(stack)
# 找到中点前一个位置
mid_num = (n - 1) // 2
p = head
while mid_num:
# 弹出栈顶
tmp = stack.pop()
# 与链头拼接(带头结点)
tmp.next = p.next
p.next = tmp
# 移动一个位置
p = tmp.next
mid_num -= 1
# 将最后一个节点的next赋None
stack.pop().next = None
题目2
题解2
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
if head is None:
return False
fast = slow = head
# 快慢指针法,时间复杂度O(n)
while slow and fast.next:
slow = slow.next
fast = fast.next.next
if fast is None or slow is None:
return False
if fast == slow:
return True
题目3
题解3
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
if head is None:
return None
slow = fast = head
pointer = head
while slow and fast.next:
slow = slow.next
fast = fast.next.next
if fast is None or slow is None:
return None
if fast == slow:
break
else:
return None
while head != slow:
head = head.next
slow = slow.next
return head