Linked list in java

0


 In this article we will see how can we perform the linked list operations like insertion, deletion, search .





import java.util.Scanner;
class NodeD
{
int data;
NodeD next;
NodeD(int data)
{
this.data=data;
this.next=null;
}
}
public class LinkedList {

public static void print(NodeD head)
{
NodeD curr=head;
while(curr !=null)
{
System.out.print(curr.data+" ");
curr=curr.next;
}
}

public static NodeD Insertbegin(NodeD head,int data)
{
NodeD temp=new NodeD(data);
temp.next=head;
return temp;
}

public static NodeD Insertend(NodeD head,int data)
{
NodeD temp=new NodeD(data);
if(head ==null)
return temp;
NodeD curr=head;
while(curr.next !=null)
{
curr=curr.next;
}
curr.next=temp;
return head;
}

public static NodeD Deletebegin(NodeD head)
{
if(head==null)
return null;
return head.next;
}

public static NodeD Deleteend(NodeD head)
{
if(head==null)
return null;
if(head.next==null)
return null;
NodeD curr=head;
while(curr.next.next !=null)
{
curr=curr.next;
}
curr.next=null;
return head;
}

public static int search(NodeD head,int data)
{
int pos=0;
if(head==null)
{
return -1;
}
NodeD curr=head;
while(curr !=null)
{
if(curr.data==data)
return pos;
curr=curr.next;
pos++;
}
return -1;
}
public static void main(String args[])
{
NodeD head1=new NodeD(1);
NodeD head2=new NodeD(2);
NodeD head3=new NodeD(3);

head1.next=head2;
head2.next=head3;

System.out.println("List is :-");
print(head1);

head1=Insertbegin(head1,0);
System.out.println("\nList after insertion at beginning is :-");
print(head1);

head1=Insertend(head1,4);
System.out.println("\nList after insertion at ending is :-");
print(head1);

head1=Deletebegin(head1);
System.out.println("\nList after deletion at beginning is :-");
print(head1);

head1=Deleteend(head1);
System.out.println("\nList after deletion at ending is :-");
print(head1);

Scanner sc=new Scanner(System.in);
System.out.println("\nEnter the value that you want to search :- ");
int value=sc.nextInt();
int index=search(head1,value);
System.out.println("value is found at "+index);
}
}


Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !