Tuesday, February 10, 2009

Doubly-ended Code Implementation :

/* Program name: A Double Ended List
Programmer: Marjorie T. Egot
Purpose: To implement a double ended linked list.
Instructor: Dony Dongiapon
Subject: IT123 Data Structures */

//a class that contains the constructor
class Link
{
public int iData;
public double dData:
public Link next;

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

//displays the elements in the list
public void displayLink()
{
System.out.print("{"+iData+","dData+"}");
}
}


//a class which contains the methods

class DoubleEndList
{
private Link first;
private Link last;


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

//this is to test if there are elements in the list
public boolean isEmpty()
{
return (first == null);
}


//inserting a node in the list to become the 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 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;
}

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

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

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



/* the main class or the application of the program.*/

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);

//displays the elements of the list
System.out.println(theList);

//apply the deletion method on the first and last element of the list
theList.deleteFirst();
theList.deleteLast();
System.out.println(theList);
}
}

No comments:

Post a Comment