Display A Linkedlist

Try First, Check Solution later

1. You should first read the question and watch the question video.
2. Think of a solution approach, then try and submit the question on editor tab.
3. We strongly advise you to watch the solution video for prescribed approach.

1. You are given a partially written LinkedList class.
2. Here is a list of existing functions:
2.1 addLast - adds a new element with given value to the end of Linked List
3. You are required to complete the body of display function and size function
3.1. display - Should print the elements of linked list from front to end in a single line. Elements should be separated by space.
3.2. size - Should return the number of elements in the linked list.
4. Input and Output is managed for you.
Input Format
Input is managed for you
Output Format
Output is managed for you
Question Video
Sample Input
addLast 10
addLast 20
addLast 30
addLast 40
addLast 50
Sample Output
10 20 30 
10 20 30 40 50

  • Editorial

    The problem deals with displaying the linked list and size of the list on the output terminal.

    We are given a linked list class which has three data members:

    1. Head: It points to the starting node of the linked list.

    2. Tail: It points to the last node of the linked list.

    3. Size: It stores the current length (or size) of the linked list.

    We now need to implement two functions. The first function expects a return value equal to the size of the list. As we already know that we have a size data member so here we just need to return it. The second function expects an output that displays the linked list. To achieve this, we need to traverse the entire list to get every element and print its value, for that we can take a temporary node starting from the head and incrementing itself until it becomes null, and for every node, we print the node data.

    Below is the implementation in Java:

    public int size(){
                                        return size;
                                    public void display(){
                                        for(Node temp = head; temp != null; temp = temp.next){
                                        System.out.print(temp.data + " ");

    java false

    Time Complexity

    The time complexity for the size() function is constant (or O(1)) since all we have to do is to return the data member size.

    The time complexity for the display() function is O(n) where n is the length of the list, as here we visit each node of the list which is dependent on the length of the list.

    Space Complexity: O(1)

    The space complexity for both the functions is constant.

  • Asked in Companies
  • Related Topics

Video Solution

Code Solution

Id Name