欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

Power Buckle Simple 876. 链表的中间节点 - 问题解决

最编程 2024-09-29 17:25:28
...

法一:

class Solution {
    public ListNode middleNode(ListNode head) {
        ListNode cur = head;
        int n = 0;
        while (cur != null) {
            n++;
            cur = cur.next;
        }
        ListNode curr = head;
        for (int i = 0; i < n / 2; i++) {
            curr = curr.next;
        }
        return curr;
    }
}

法二:快慢指针

class Solution {
    public ListNode middleNode(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        while(true){
            if(fast == null || fast.next == null){
                break;
            }
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }
}