876. 链表的中间结点🔖链表

876. 链表的中间结点🔖链表

876. 链表的中间结点https://leetcode-cn.com/problems/middle-of-the-linked-list/问题描述问题分析代码实现js/** * Definition for singly-linked list. * function ListNode...

2020年11月30日
152字
12 阅读


876. 链表的中间结点

问题描述

问题分析

代码实现

js

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var middleNode = function(head) {
    let count = 0
    let temp = head
    while(temp) {
        count++
        temp = temp.next
    }
    for(let i = 0; i < (count-1)/2; i++) {
        head = head.next
    }
    return head
};

java

class Solution {
    public ListNode middleNode(ListNode head) {
        if (head.next == null) return head;
        if (head.next.next == null) return head.next;

        ListNode slow = head.next;
        ListNode fast = head.next.next;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (fast == null) return slow;
        }
        return slow;
    }
}


文章评论区

欢迎留言交流

未登录,请先注册或登录后发表评论。

Leave comment