[LeetCode] 876. Middle of the Linked List

发布时间:2019-06-05 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了[LeetCode] 876. Middle of the Linked List脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

Problem

Given a non-empty, singly linked list with head node head, return a middle node of linked list.

If there are two middle nodes, return the second middle node.

Example 1:

Input: [1,2,3,4,5]
Output: Node 3 from this list (Serialization: [3,4,5])
The returned node has value 3. (The judge's serialization of this node is [3,4,5]).
Note that we returned a ListNode object ans, such that:
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 from this list (Serialization: [4,5,6])
Since the list has two middle nodes with values 3 and 4, we return the second one.

Note:

The number of nodes in the given list will be between 1 and 100.

Solution

SOL.1

class Solution {
    public ListNode middleNode(ListNode head) {
        ListNode fast = head, slow = head;
        
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        
        return slow;
    }
}

SOL.2

class Solution {
    public ListNode middleNode(ListNode head) {
        ListNode fast = head, slow = head;
        int n = 1;
        while (fast.next != null) {
            fast = fast.next;
            n++;
        }
        int k = n/2;
        while (k != 0) {
            slow = slow.next;
            k--;
        }
        return slow;
    }
}

脚本宝典总结

以上是脚本宝典为你收集整理的[LeetCode] 876. Middle of the Linked List全部内容,希望文章能够帮你解决[LeetCode] 876. Middle of the Linked List所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: