Implement Linked List using Java
import java.util.*;
import java.io.*;
import java.lang.*;
class Linked
{
int val;
Linked next;
Linked(int g)
{
val=g;
next=null;
}
void addNode(int p)
{
Linked ob=new Linked(p);
Linked t;
t=this;
while(t.next!=null)
{
t=t.next;
}
t.next=ob;
}
void disp()
{
Linked t;
t=this;
while(t!=null)
{
System.out.println(t.val);
t=t.next;
}
}
}
class LinkedPrg
{
public static void main(String []ar) throws IOException
{
Scanner cin=new Scanner(System.in);
int p,g;
char ch='y';
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the value for the head node : ");
g=Integer.parseInt(br.readLine());
Linked ob=new Linked(g);
while(true)
{
System.out.println("Do you want to continue?(y/n) : ");
ch=br.readLine().charAt(0);
if(ch=='n' || ch=='N')
break;
System.out.println("Enter the value for the node : ");
g=Integer.parseInt(br.readLine());
ob.addNode(g);
}
System.out.println("\n\nValues are : ");
ob.disp();
}
}
I/O : save this program using LinkedPrg.java. run this program. hope u will be able to understand the code.
import java.io.*;
import java.lang.*;
class Linked
{
int val;
Linked next;
Linked(int g)
{
val=g;
next=null;
}
void addNode(int p)
{
Linked ob=new Linked(p);
Linked t;
t=this;
while(t.next!=null)
{
t=t.next;
}
t.next=ob;
}
void disp()
{
Linked t;
t=this;
while(t!=null)
{
System.out.println(t.val);
t=t.next;
}
}
}
class LinkedPrg
{
public static void main(String []ar) throws IOException
{
Scanner cin=new Scanner(System.in);
int p,g;
char ch='y';
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the value for the head node : ");
g=Integer.parseInt(br.readLine());
Linked ob=new Linked(g);
while(true)
{
System.out.println("Do you want to continue?(y/n) : ");
ch=br.readLine().charAt(0);
if(ch=='n' || ch=='N')
break;
System.out.println("Enter the value for the node : ");
g=Integer.parseInt(br.readLine());
ob.addNode(g);
}
System.out.println("\n\nValues are : ");
ob.disp();
}
}
I/O : save this program using LinkedPrg.java. run this program. hope u will be able to understand the code.
Comments
Post a Comment