876. Middle of the Linked List

/*
876. Middle of the Linked List
https://leetcode.com/problems/middle-of-the-linked-list/description/

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.
**/
class Solution {
    fun middleNode(head: ListNode?): ListNode? {
        var cur = head;
        var cur2 = head;
        var count = 0
        while(cur!=null){
            count++
            cur = cur.next
        }
        var half = count/2
        while (half>0){
            cur2 = cur2?.next
            half--
        }
        return cur2
    }
}

 

posted @ 2020-04-09 12:43  johnny_zhao  阅读(103)  评论(0编辑  收藏  举报