Sunday, February 15, 2009

Stack (Java Code Implementation)

/* Programmer: Chrisdyll P. Pellejo
Program name: A Stack Code Implementation
Purpose: To implement a Stack Code.
Instructor: Dony Dongiapon
Subject: IT123 Data Structures*/

//a class which declares the variables and the constructors
class Link{
public int iData=0;//data item


public Link(int iData, ) //constructor
{
iData=id;

}

public void displayLink() //displaying the data
{
System.out.println(iData+":" );
}
}

//the class which contains the methods or the operations on the stack
class StackList{
private Link first;

public StackList(){ //declaring the list as empty or null
first=null;

}

public boolean isEmpty() { //checking if the list is empty or not
return (first == null);
}

public void insertFirst( int id) { //insertion operation
Link newLink = new Link( id);
newLink.next = first;
first = newLink;
}

public Link deleteFirst() //deletion operation
{
Link temp=first;
return temp;
}

public Link pick() //determining the top of the list but doing nothing with it
{
Link temp=first;
return temp;
}

public void displayList //display the data
{
System.out.print("Elements on the stack: ");
Link temp=first;
while(temp!=null)
{
temp.displayList();
}

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

//the main class which applies the methods on the stack
class StackListApp
{
public static void main (String[]args)
{
StackList theList=new StackList();

theList.insertFirst(12);
theList.insertFirst(25);
theList.insertFirst(91);

//when deleting
//just erase the comment if you want to run the method of deletion
theList.deleteFirst();

//when displaying the element
theList.displayList();
}
}

No comments:

Post a Comment