Before creating the linked list first we need to create individual links this can be achieved with the help of a special class called as Self referential class Link
class Link
{
public int rollNo;
public String name;
public Link next;
public Link(int rNo,String n)
{
rollNo=rNo;
name=n;
}
public void displayLink()
{
System.out.print("{"+rollNo+","+name+"}");
}
}
Here the
rollNo and name are the information associated with the node and next is the
referential variable to hold the address of the next node in the list.
The LinkList Class
The
LinkList class contains only one element called as first which is used to
maintain the address of first link in the list. Since in order to process the
list, it’s mandatory to know the starting address of the list. Using the first
link address all the Links can be processed very easily.
Basic
operations on Single Linked lists
·
Inserting an item at the beginning of the list.
·
Deleting the item at the beginning of the list.
·
Display the contents of the entire list.
class
LinkList
{
private Link first;
public void LinkList( )
{
first = null;
}
public
boolean isEmpty( )
{
return(first==null);
}
public
void insertFirst( ----)
{
======
}
public
Link deleteFirst()
{
=====
}
public void displayList()
{
======
}
}
Here insertFirst() - inserts a Link at the beginning of the Linked List
deleteFirst() - removes a Link at the beginning of the Linked List
displayList() - used to traverse to display all the Links in the LinkedList
Java program to perform basic operations of Single Linked List
class LinkList
{
public Link first;
public LinkList()
{
first=null;
}
public boolean isEmpty()
{
return (first==null);
}
public void insertFirst(int rNo,String n)
{
Link L=new Link(rNo,n);
L.next=first;
first=L;
}
public
Link deleteFirst()
{
Link temp=first;
first=first.next;
return temp;
}
public void displayList()
{
System.out.print("\nList:[");
Link current=first;
while(current!=null)
{
current.displayLink();
current=current.next;
}
System.out.println("]");
}
}
public
class LinkListApp
{
public static void main(String[] args)
{
LinkList LST=new LinkList();
//adding the elements into the LinkedList
LST.insertFirst(17001,
"Raju");
LST.insertFirst(17002,
"Divya");
LST.insertFirst(17003,
"Hari");
LST.insertFirst(17004,
"Teja");
//Displaying the Links in the LinkedList
LST.displayList();
// Deleting Link from the LinkedList
Link temp=LST.deleteFirst();
System.out.println("Deleted LInk
:");
temp.displayLink();
LST.displayList();
}
}
No comments:
Post a Comment