Sunday, February 15, 2009

Stack Implementation

A. Definition/ Concept:

♥Always remember that the stack is a very common data structure used in programs. By data  structure, we mean something that is meant to hold data and provides certain operations on that data.[1]
♥Stacks are linear data structures. This means that their contexts are stored in what looks like a line (although vertically). This linear property, however, is not sufficient to discriminate a stack from other linear data structures. For example, an array is a sort of linear data structure in which you can access any element directly. In contrast, in a stack, you can only access the element at its top.[2]
♥Since a stack usually holds a bunch of items with the same type, we could implement a stack as an array. [www.google.com]


B. java Code:


//purpose: To implement an array of list in a certain Stack


public class LLStack{
private java.util.LinkedList list=nw java.util.LinkedList();
public LLStack(){
}
public void clear(){
list.clear();
}
public boolean isEmpty(){
return list.isEmpty();
}
public Object topEl(){
if(isEmpty())
throw new java.util.EmptyStackException();
return list.getLast();
}
public Object pop(){
if(isEmpty())
throw new java.util.EmptyStackException();
return list.removeLast();
}
public void push(Object el){
list.addLast(el);
}
public String toString(){
return list.toString();
}
}


C. References:

[1]Data structures and algorithms in Java 2nd Edition by: Adam Drozdek
[2]http://www.cs.bu.edu/teaching/c/stack/linked-list/

No comments:

Post a Comment