Tuesday, February 17, 2009

Doubly-Linked List

//this is the implementation of
//Doubly-Linked List

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);
}
public void insertFirst(int id,double dd) { //method for insertFirst
Link newLink = new Link(id,dd);
if (isEmpty ())
last = newLink;
newLink.next = first;
first = newLink;
}
public void insertLast(int id,double dd) { //method for insertLast
Link newLink = new Link(id,dd);
if (isEmpty()
first = newLink;
else
last.next = newLink;
last = newLink;
}
public Link deleteFirst(int id,double dd) { //method for deletion
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 FirstLastApps{ //for application
public static void main(String[] args) {
FirstLastList theList = new FirstLastList();

theList.insertFirst(16,3.89);
theList.insertFirst(56,6.45);
theList.insertLast(26,5.00);
theList.insertLast(86,6,90);


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

No comments:

Post a Comment