LeetCode:876. Middle of the Linked List

題目:
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.

範例:

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.

解法:
給一個LinkList
回傳中間的的節點

所以要先歷遍LinkList算出有幾個節點
算出總數後除2找到中間值
並回傳該節點

程式碼:

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func middleNode(head *ListNode) *ListNode {
    var NowNode = new(ListNode)
    var NodeCount = 0
    
    NowNode = head
    for {
        if NowNode.Next == nil {
            break
        }
        NowNode = NowNode.Next
        NodeCount++
    }
    
    ReturnCount := math.Ceil(float64(NodeCount)/2)
    
    NowNode = head
    count := 0.0
    for {
        if count==ReturnCount {
            break;
        }
        NowNode = NowNode.Next
        count++;
    }
    return NowNode
}

感覺有點冗長…

發佈留言