linkedList print nodes method

Linked List Print Nodes Method

If you are working with linked lists, you will often need to print the nodes in the list. This can be done using a print nodes method that iterates through the list and prints the data of each node. The method should take the head of the list as a parameter.

Method 1: Using a While Loop

One way to print the nodes in a linked list is to use a while loop that iterates through the list until it reaches the end. Here is an example:


public void printNodes(Node head) {
  Node current = head;
  
  while(current != null) {
    System.out.print(current.data + " ");
    current = current.next;
  }
}

This method starts with the head of the list and uses a while loop to iterate through each node, printing its data. It then moves on to the next node until it reaches the end of the list.

Method 2: Using Recursion

Another way to print the nodes in a linked list is to use recursion. This method is more elegant, but also less efficient than the while loop method. Here is an example:


public void printNodes(Node head) {
  if(head == null) {
    return;
  }
  
  System.out.print(head.data + " ");
  printNodes(head.next);
}

This method starts with the head of the list and checks if it is null. If it is, the method returns. If it is not null, the method prints the data of the current node and then calls itself with the next node as a parameter. This process continues until it reaches the end of the list.

Both of these methods can be used to print the nodes in a linked list. The while loop method is more efficient and easier to understand, while the recursion method is more elegant but less efficient.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe