LintCode: Count Linked List Nodes

Count Linked List Nodes



Similar Problems:


Description

Count how many nodes in a linked list.

Example

Given 1->3->5, return 3.

Github: code.dennyzhang.com

Credits To: lintcode.com

Leave me comments, if you have better ways to solve.


  • Solution:
// Blog link: https://code.dennyzhang.com/count-linked-list-nodes
// Basic Ideas: One pass
// Complexity: Time O(n), Space O(1)
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */

/**
 * @param head: the first node of linked list.
 * @return: An integer
 */
func countNodes (head *ListNode) int {
    res, p := 0, head
    for p != nil {
        p = p.Next
        res++
    }
    return res
}
linkedin
github
slack

Share It, If You Like It.

Leave a Reply

Your email address will not be published.