Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package stackPractice;
- /**
- *
- * @author acer
- */
- public class ListStack implements Stack {
- // The number of items on the stack
- int size;
- Node top;
- int capacity;
- public ListStack(){
- top=null;
- size=0;
- }
- public int size(){
- int count=0;
- for(Node n=top;n!=null;n=n.next){
- count++;
- }
- return count;
- }
- // Returns true if the stack is empty
- public boolean isEmpty(){
- if(top==null){
- return true;
- }else{
- return false;
- }
- }
- // Pushes the new item on the stack, throwing the
- // StackOverflowException if the stack is at maximum capacity. It
- // does not throw an exception for an "unbounded" stack, which
- // dynamically adjusts capacity as needed.
- public void push(Object e) throws StackOverflowException{
- Node mn=new Node(e,null);
- mn.next=top;
- top=mn;
- size++;
- }
- // Pops the item on the top of the stack, throwing the
- // StackUnderflowException if the stack is empty.
- public Object pop() throws StackUnderflowException{
- Node rn=top;
- Object val=rn.element;
- top=top.next;
- rn.element=null;
- rn.next=null;
- size--;
- return val;
- }
- // Peeks at the item on the top of the stack, throwing
- // StackUnderflowException if the stack is empty.
- public Object peek() throws StackUnderflowException{
- if(top==null)
- throw new StackUnderflowException();
- return top.element;
- }
- // Returns a textual representation of items on the stack, in the
- // format "[ x y z ]", where x and z are items on top and bottom
- // of the stack respectively.
- public String toString(){
- String str="[";
- for(Node n=top;n!=null;n=n.next){
- if(n.next==null){
- str+=n.element+"]";
- }
- else{
- str+=n.element+",";
- }
- }
- return str;
- }
- // Returns an array with items on the stack, with the item on top
- // of the stack in the first slot, and bottom in the last slot.
- public Object[] toArray(){
- Object [] arr=new Object[size];
- int i=0;
- for(Node n=top;n!=null;n=n.next){
- arr[i]=n.element;
- i++;
- }
- return arr;
- }
- // Searches for the given item on the stack, returning the
- // offset from top of the stack if item is found, or -1 otherwise.
- public int search(Object e){
- int idx=-1;
- int count=0;
- for(Node n=top;n!=null;n=n.next){
- if(e.equals(n.element)){
- idx=count;
- }
- count++;
- }
- return idx;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment