Tuesday, June 7, 2016

Linked List Discussion in Core-Java

Linked-Lists :

As we know that Arrays had certain disadvantages as data storage structures .in an unordered array ,searching is slow,where as in an ordered array insertion is slow.in both the kinds of the arrays,deletion is slow. Also,the size of the array can not be changed.

Linked-List is  a storage structure which solves both these problems.In fact you can use a linked list in many cases in which you use an array,unless you need frequent random access to individual items using an index.

Links:

In a linked-list,each item is embedded in a link. A link is an object of a class called something like Link.because there are many similar links in a list,it make sense to use a separate class for them,distinct from the linked list itself.This kind of class is sometimes called as self-referential because it contains a field--called next in this case--of the same type as itself.

Simple Linked-List Operations code example:


/**
 *
 */

/**
 * @author Abhinaw.Tripathi
 *
 */

class Link
{
  public int iData;
  public double dData;
  public Link next;
 
  public Link(int id,double dd) {
this.dData=dd;
this.iData=id;
 }
 
  public void displayLink()
  {
 System.out.println("{ "+ iData + "," +dData + "} ");
  }

}

class LinkList
{
 private Link first;

 public LinkList() {
first=null;
}

public boolean isEmpty()
{
return (first == null);
}

public void insertFirst(int id,double dd)
{
Link newLink=new Link(id, dd);
newLink.next=first;
first=newLink;
}

public Link deleteFirst()
{
Link temp=first;
first=first.next;
return temp;
}

public void displayList()
{
System.out.println("List (first to last-----> ):");
Link current=first;
while(current!=null)
{
current.displayLink();
current=current.next;
}
System.out.println(" ");
}

}


public class LinkListTest {

public static void main(String[] args) {

LinkList theList=new LinkList();
theList.insertFirst(22, 2.99);
theList.insertFirst(44, 3.99);
theList.insertFirst(99, 6.99);
theList.insertFirst(88, 4.99);

theList.displayList();
while(!theList.isEmpty())
{
Link aLink=theList.deleteFirst();
System.out.println("Deleted ");
aLink.displayLink();
System.out.println(" ");
}

}


}

No comments: