Linked list
Linked list
next node. This structure allows nodes to be dynamically linked together, forming a
chain-like sequence.
Node Structure
----------------------------------------------
public class Node{
int data;
Node next;
public Node(int data)
{
this.data=data;
this.next=null;
}
1. Traversal of Singly Linked List
-------------------------------------------------------
Traversal of Singly Linked List is one of the fundamental operations, where we
traverse or visit each node of the linked list.
We will initialize a temporary pointer to the head node of the singly linked list.
After that, we will check if that pointer is null or not null, if it is null, then
return.
While the pointer is not null, we will access and print the data of the current
node, then we move the pointer to next node.
import java.util.*;
class Node{
int data;
Node next;
Node(int data){
this.data=data;
this.next=null;
}
}
class Main{
public static void traversal(Node head){
while(head!=null){
System.out.print(head.data+"-->");
head=head.next;
}
System.out.println("null");
}
public static void main(String[] args){
Node head=new Node(10);
head.next=new Node(20);
head.next.next=new Node(30);
traversal(head);
}
}
-----------------------------------------------------------
Search an element in a linked list
import java.util.*;
class Node{
int data;
Node next;
Node(int data){
this.data=data;
this.next=null;
}
}
public class Main{
public static boolean search(Node head,int key){
Node cur=head;
while(cur!=null){
if(cur.data==key){
return true;
}
cur=cur.next;
}
return false;
}
public static void main(String args[]){
Node head=new Node(10);
head.next=new Node(20);
int key=30;
if( search(head,key))
System.out.println("yes");
else
System.out.println("No");
}
}
------------------------------------------------------------------------
Length of a linked list
import java.util.*;
class Node{
int data;
Node next;
Node(int data){
this.data=data;
this.next=null;
}
}
public class Main{