Saturday, November 28, 2015

Stack Implementation using Linked List

This is a Stack Implementation using LinkedList in Java. As in Java we don't have pointers and hard to remove head node in a empty list, we are using a dummy head node.

public class Stack {
    Stack next;
    int data;
    private int size;
    public Stack() {
        this.size=-1;
        this.data=-999; //Garbage Value to denote Head
        this.next=null;
    }
    public Stack(int data) {
        this.data=data;
        this.next=null;
    }
    public void push(int... data)    {
        int s = data.length;
        for(int i=0; i<s; i++)
            push(data[i]);
    }
    public void push(int data)    {
        Stack S = this;
        if(size==-1)    {
            S.next=new Stack(data);
        }    else    {
            Stack newNode = new Stack(data);
            newNode.next=S.next; //Head is a dummy node here
            S.next=newNode;
        }
        size++;
    }
    public final static int ErrorCode = -999;
    public int pop()    {
        Stack S = this;
        if(size>-1)    {
            int value = S.next.data;
            S.next=S.next.next;
            size--;
            return value;
        }    else    {
            System.out.println("Error: Stack is Empty");
            return ErrorCode;
        }
    }
    public int size()    {
        return size;
    }
    public int peek()    {
        Stack S = this;
        if(size>-1)    {
            return S.next.data;
        }    else    {
            System.out.println("Error: Stack is Empty");
            return ErrorCode;
        }
    }
    public void printStack()    {
        Stack S = this;
        S=S.next; // first node is dummy
        StringBuffer sb = new StringBuffer();
        while(S!=null)    {
            sb.append(S.data).append(", ");
            S=S.next;
        }
        System.out.println(sb.toString());
    }
}

No comments:

Post a Comment

UA-39217154-2