链表算法之【链表的中间节点】
目录
LeetCode-876题
LeetCode-876题
给定单链表的头节点head,请找出链表的中间节点并返回,如果有两个中间节点,则返回第二个中间节点
class Solution {/*** 这里采用的是双指针的解法*/public ListNode middleNode(ListNode head) {// checkif (head == null)return null;if (head.next == null)return head;// 定义双指针(快慢指针)ListNode slow = head;ListNode fast = head;// 慢指针一次前进一个节点// 快指针一次前进两个节点while (fast != null && fast.next != null) {slow = slow.next;fast = fast.next.next;}// 此时慢指针指向的是链表的中间节点return slow;}private static class ListNode {int val;ListNode next;public ListNode() {}public ListNode(int val) {this.val = val;}public ListNode(int val, ListNode next) {this.val = val;this.next = next;}}
}