Skip to content
the poor coder

linkedList print nodes method

Poor Man
Published
Reading time
1 min read
On this page

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:

Java

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:

Java

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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC