How to get the Intermediate Node of linked list in leetcode
This article mainly introduces how to get the middle node of the linked list in leetcode. It is very detailed and has a certain reference value. Friends who are interested must read it!
The middle node of a linked list
Given a non-empty single linked list with header node head, return the middle node of the linked list.
If there are two intermediate nodes, the second intermediate node is returned.
Example 1: input: output: node 3 in this list (serialized form: [3Power4]) returns a node value of 3. (the serialization of the node is described by the evaluation system as [3pr 4je 5]. Notice that we return an object of type ListNode ans, such as ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NULL.
Example 2: input: output: node 4 in this list (serialized form: [4Power5]) because the list has two intermediate nodes with values of 3 and 4 respectively, we return the second node. Tip: the number of nodes in a given linked list is between 1 and 100.
Train of thought:
When it comes to linked lists, whether single linked lists or double linked lists, it is not difficult to draw and analyze them.
The general routine solution is to use fast and slow pointers, or to use auxiliary lists to solve problems.
# Definition for singly-linked list.# class ListNode:# def _ init__ (self, x): # self.val = x # self.next = None
Class Solution: def middleNode (self Head: ListNode)-> ListNode: if head is None or head.next is None: return head # Auxiliary list''l = [] while head: l.append (head) head = head.next return l [len (l) / / 2]''# Fast and slow pointer # slow take one step Fast takes two steps at a time, and when fast comes to the end, slow goes to the middle slow = head fast = head while fast and fast.next: slow = slow.next fast = fast.next.next return slow
The above is all the content of the article "how to get the middle node of the linked list in leetcode". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!