Sunday, February 15, 2009

Implementation of Double Ended Link List

// To implement a double ended link list.

//constructor
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 FirstLastList {

private Link first;
private Link last;

public FirstLastList() {

first = null;
last = null;

}

public boolean isEmpty() {

return (first == null);

}
// inserting a node in first element

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 in a last element

public void insertLast(int id,double dd) {

Link newLink = new Link(id,dd);

if (isEmpty())
first = newLink;

else

last.next = newLink;
last = newLink;
}

// delete the first node in the list
public Link deleteFirst(int id,double dd) {
int temp = first.iData;
if (first.next == null)
last = null;
first = first.next;
return temp;
}

// delete the last node in a list
public Link deleteLast(int id, double dd){
int temp=last.iData;
if(last.next==null)
first=null;
last=last.next;
return temp;
}
// display an element in a list
public void displayList(){
System.out.print("List(first-->Last);");
Link current=first;
while(current!=null){
current.displayLink();
current=current.next;
}

}
System.out.println(" ");
}

}

//main method to apply
public class FirstLastApp{

public static void main(String[] args) {

FirstLastList theList = new FirstLastList();

theList.insertFirst(19,1.90);
theList.insertFirst(13,1.9);
theList.insertFirst(25,5.62);
theList.insertLast(24,6.8);
theList.insertLast(23,3.79);
theList.insertLast(56,2.25);

System.out.println(theList);

theList.deleteFirst();

theList.deleteFirst();

System.out.println(theList);
}

}

No comments:

Post a Comment