Data Structures using Java
Array Traversal – Pointer Implementation
import java.io.*;
import java.util.*;
public class LinkedList {
Node head;
static class Node {
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
public static LinkedList insert(LinkedList list, int data)
{
Node new_node = new Node(data);
if (list.head == null) {
list.head = new_node;
}
else {
Node last = list.head;
while (last.next != null) {
last = last.next;
}
last.next = new_node;
}
return list;
}
public static void search(LinkedList list, int x)
{
Node currNode = list.head;
System.out.print("Search Result : ");
while (currNode != null) {
if(currNode.data==x){
System.out.print("The data "+ currNode.data + " is found in the
list");
}
currNode = currNode.next;
}
public static void traversal(LinkedList list)
{
Node currNode = list.head;
System.out.print("LinkedList: ");
while (currNode != null) {
SR, Department of Data Science, SXC Page | 1
Data Structures using Java
System.out.print(currNode.data + " ");
currNode = currNode.next;
}
}
public static void main(String[] args)
{
LinkedList list = new LinkedList();
System.out.println("Enter the size of the list to be created : ");
Scanner s= new Scanner(System.in);
int n= s.nextInt();
System.out.println("\nYou will be allowed to create a list of size "+n);
System.out.println("\nInsert operation in progress.....");
for(int i=0; i<n;i++){
System.out.println("Enter the "+ i + "th element to insert : ");
int a= s.nextInt();
list = insert(list, a);
}
System.out.println("\nTraversal operation in progress.....");
traversal(list);
System.out.println("\nTraversal operation have completed .....");
System.out.println("\nSearch operation in progress .....");
System.out.println("Enter the element to find : ");
int b= s.nextInt();
search(list, b);
}
}
SR, Department of Data Science, SXC Page | 2