美文网首页
LeetCode 第876题:链表的中间结点

LeetCode 第876题:链表的中间结点

作者: 放开那个BUG | 来源:发表于2020-08-12 15:27 被阅读0次

1、前言

题目描述

2、思路

画个图尝试一下即可。

3、代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode middleNode(ListNode head) {
        if(head == null || 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;
    }
}

相关文章

网友评论

      本文标题:LeetCode 第876题:链表的中间结点

      本文链接:https://www.haomeiwen.com/subject/pdwddktx.html