Leetcode brushing record (10): the intermediate node of the 876 linked list

Brush questions website: Leetcode

Difficulty: easy

Language: Python

Plan : From easy -> to medium -> to hard.

1. The intermediate node of the 876 linked list

1.1 Subject:

Given a non-empty singly linked list whose head node is head, return the middle node of the linked list.

If there are two intermediate nodes, return the second intermediate node.

  • Example 1
输入:[1,2,3,4,5]
输出:此列表中的结点 3 (序列化形式:[3,4,5])
返回的结点值为 3(测评系统对该结点序列化表述是 [3,4,5])
注意,我们返回了一个 ListNode 类型的对象 ans,这样:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, 以及 ans.next.next.next = NULL.
  • Example 2
输入:[1,2,3,4,5,6]
输出:此列表中的结点 4 (序列化形式:[4,5,6])
由于该列表有两个中间结点,值分别为 34,我们返回第二个结点。

1.2 Thinking and Analysis

The title gives the term singly linked list , which refers toThe data in the table is represented by nodes, and each node consists of elements (images of data elements) and pointers (successor element storage locations).

We have done so many double pointer problems before, basically using the left and right colliding pointers. This problem can be done with the fast and slow pointers in the double pointer . The fast and slow pointers have been indicated in my previous study notes , and this blog introduces them in great detail.

The basic concepts refer to:The two pointers start to traverse the array from the same direction, which are defined as fast pointer (fast) and slow pointer (slow) respectively, and move in different strategies until the values ​​of the two pointers are equal. Assuming fast moves 2 pointers at a time, slow moves 1 pointer at a time. When fast reaches the tail node and points to NULL, slow is just at the middle node of the linked list.

Therefore, back to this question, we consider doing it with fast and slow pointers.

First define the fast and slow pointers according to the linked list

slow = head
fast = head

Then two pointers are needed to move with this, and finally the slow value is returned, that is, the intermediate node.

The complete code is as follows:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def middleNode(self, head: ListNode) -> ListNode:
        slow = head
        fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
        return slow

The execution result is as follows
insert image description here

1.3 Summary

Pay special attention, this question is done with fast and slow pointers, and I am still confused at first, knowing the usage of fast and slow pointers is easy to do. The above code is the basic format of the fast and slow pointer, which needs to be remembered for subsequent use.

Guess you like

Origin blog.csdn.net/A33280000f/article/details/121249154