leetcode-4.19[143. 重排链表、141. 环形链表、142. 环形链表 II](python解法)

题目1

leetcode-4.19[143. 重排链表、141. 环形链表、142. 环形链表 II](python解法)_第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

leetcode-4.19[143. 重排链表、141. 环形链表、142. 环形链表 II](python解法)_第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

leetcode-4.19[143. 重排链表、141. 环形链表、142. 环形链表 II](python解法)_第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

附上题目链接:

题目1链接
题目2链接
题目3链接

你可能感兴趣的:(LeetCode,链表,leetcode,websphere,回环列表,Python)