Java Program to Create a Singly Linked List and Count the Number of Nodes
Linked List is a linear data structure. Linked list elements are not stored at a contiguous location, the elements are linked using pointers. Singly Linked list is the collection of nodes, where each node has two parts one is the data and other is the linked part.
Example:
Input : AddNodes = {2, 3, 4}
Output: LinkedList = [2, 3, 4]
Size = 3
Input : AddNodes = {1, 2, 3, 4, 5}
Output: LinkedList = [1, 2, 3, 4, 5]
Size = 5
Operations:
- Create Node linked list
- Define methods like addNode(),displayNodes() and countNodes()
- Get the final answer
Implementation:
Java
import java.io.*;
import java.util.*;
public class LinkedListCreation {
class Node {
int data;
Node next;
Node( int data)
{
this .data = data;
this .next = null ;
}
}
Node head = null ;
Node tail = null ;
void addNode( int data)
{
Node newNode = new Node(data);
if (head == null ) {
head = newNode;
tail = newNode;
}
else {
tail.next = newNode;
tail = newNode;
}
}
void displayNodes()
{
Node current = head;
if (head == null ) {
System.out.println( "Empty" );
return ;
}
System.out.println( "Nodes : " );
while (current != null ) {
System.out.print(current.data + " " );
current = current.next;
}
System.out.println();
}
int countNodes()
{
int count = 0 ;
Node currentNode = head;
while (currentNode != null ) {
count++;
currentNode = currentNode.next;
}
return count;
}
public static void main(String[] args)
{
LinkedListCreation L1 = new LinkedListCreation();
L1.addNode( 1 );
L1.addNode( 2 );
L1.addNode( 3 );
L1.addNode( 4 );
L1.displayNodes();
System.out.println( "Total Nodes: "
+ L1.countNodes());
}
}
|
Output
Nodes :
1 2 3 4
Total Nodes: 4
Time Complexity For new node Insertion:
- At first: O(1)
- At End: O(N), where N is the size of linked list
Time Complexity For count number of nodes: O(N), where N is a number of nodes
Auxiliary space: O(1) as it is using constant space
Last Updated :
12 Sep, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...