# Count the Number of Elements in Linked List

This blog post is a part of a series on programming interview questions. You can find more interview questions blog post here.

## Question

A common question that comes up in coding interviews is to count the number of elements in the **linked list**. Now, most linked list libraries have a function to get the number of elements but this cannot be used in interviews in most cases. In this post, I will show you one way to solve this problem.

## Example LinkedList

Here is an example linked** list** of **integers**.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
type List struct { head *Node tail *Node } // Get head / first func (list *List) First() *Node { return list.head } // Add to tell func (list *List) Add(value int) { newNode := &Node{data: value} if list.head == nil { list.head = newNode } else { list.tail.next = newNode } list.tail = newNode } |

## Counting Elements in a Linked List

To count the elements in a linked list, we start at the beginning of the linked list and count until we hit the end of the list.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
func size(list *List) int { // create variable for size var size int // set current node to head current := list.head // loop until current is nil for current != nil { // increase size by 1 size++ // set current to next node current = current.next } // return size return size } |

## Conclusion

In this blog post, you learned how to count the number of elements in a **linked list**. You can learn more about **linked lists** at GeeksforGeeks.