[LeetCode] The middle node of the linked list, given a non-empty singly linked list with the head node as head, return the middle node of the linked list. If there are two intermediate nodes, return to the second intermediate node.

learning target:

Goal: proficiently use the knowledge learned in Java


Learning Content:

The content of this article: Implemented in Java: the middle node of the linked list


Title description:

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 to the second intermediate node.

Example 1:

Input: [1,2,3,4,5]
Output: Node 3 in this list (serialized form: [3,4,5]) The returned node value is 3.
(The serialization expression of this node in the evaluation system is [3,4,5]).
Note that we returned an object ans of type ListNode, like this: ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next =
NULL.

Example 2:

Input: [1,2,3,4,5,6]
Output: Node 4 in this list (serialized form: [4,5,6]) Since this list has two intermediate nodes, the values ​​are respectively 3, 4, we return to the second node.

Problem-solving ideas:

This question needs to return to the intermediate node of the linked list, so we only need to know which node the intermediate node of the linked list is in.
First, traverse the linked list to get the length of the linked list, and then divide by two to get the intermediate node. Nodes, and then loop through the corresponding times

Implementation code:

 public static ListNode middleNode(ListNode head) {
    
    
     ListNode cur=head;
        int count=0;//保存链表长度
        //循环遍历统计长度
        while(cur!=null){
    
    
            cur=cur.next;//更新结点
            count++;
        }
        cur=head;//将cur更新至头结点
        int mid=count/2;//得到中间结点的位置
        //循环相应次数。得到中间结点
        for(int i=0;i<mid;i++){
    
    
            cur=cur.next;
        }
        return cur;//返回中间结点
    }

Guess you like

Origin blog.csdn.net/zhangxxin/article/details/114383149