Tuesday, February 17, 2009

Double Ended Linked list


Definition:
It allows for insertions in the front or in the back of the list. Each type of link list will build off of the previous one. First we'll examine the singly linked list before moving onto the double-ended and doubly linked lists. [safari books]


Doubly-ended Implementation :

class Link
{
public int iData;
public double dData:
public Link next;

public Link(int id,double dd)
{
iData = id;
dData=dd;
}

public void displayLink()
{
System.out.print("{"+iData+","dData+"}");
}
}

class DoubleEndList
{
private Link first;
private Link last;


public DoubleEndList()
{
first = null;
last = null;
}


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

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

if (isEmpty ())
last = newLink;
newLink.next = first;

first = newLink;
}

//inserting a node on the last
public void insertLast(int id,double dd)
{
Link newLink = new Link(id,dd);
if (isEmpty())
first = newLink;
else
last.next = newLink;
last = newLink;
}

public Link deleteFirst(int id,double dd)
{
int temp = first.iData;
if (first.next == null)
last = null;
first = first.next;
return temp;
}


public Link deleteLast(int id, double dd)
{
int temp=last.iData;
if(last.next==null)
first=null;
last=last.next;
return temp;
}


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

public class DoubleEndApp
{
public static void main(String[] args)
{

DoubleEndList theList = new DoubleEndList();

//apply the insertion methods on the first and the last node
theList.insertFirst(12,2.55);
theList.insertFirst(21,4.55);
theList.insertFirst(67,8.99);
theList.insertLast(18,9.99);
theList.insertLast(43,3.33);
theList.insertLast(34,5.66);

System.out.println(theList);

theList.deleteFirst();
theList.deleteLast();
System.out.println(theList);
}
}

Illustrations


Reference:
[safari books] http://my.safaribooksonline.com/30000LTI00162/ch05lev1sec2

No comments:

Post a Comment