Tuesday, December 17, 2013

Stack Programming using consturctor in JAVA : Day 7


 
 Write a program to see a practical application of the JAVA CLASS, let’s develop the Stack. A stack stores data using first-in, last-out ordering. That is, a stack is like a stack of plates on a table. The first plate put down on the table is the last plate to be used. Stacks are controlled through two operations traditionally called push and pop. Use the Class name for this program as Stack, Stack() as constructor, push() and pop() as method.

3 comments:

  1. =>

    //this class defines an integer stack that can hold 5 values.

    class Stack
    {
    int stack[]=new int [5];
    int ts;

    //Initialize top-of-stack=ts.

    Stack()
    {
    ts= -1;
    }

    //push an item on the stack

    void push(int item)
    {
    if(ts == 4)
    System.out.println("Stack is full");
    else
    stack[++ts] = item;
    }

    //pop an item from the stack

    int pop()
    {
    if(ts < 0)
    {
    System.out.println("Stack underfolw");
    return 0;
    }
    else
    return stack[ts--]
    }
    }
    class TestStack
    {
    public static void main(String args[])
    {
    Stack mystack1 = new Stack();
    Stack mystack2 = new Stack();

    //push numbers on the stack

    for(int i=0; i<5; i+=1)
    mystack1.push(i);
    for(int i=0; i<10; i+=1)
    mystack2.push(i);

    // pop those numbers off the stack

    System.out.println("Stack in mystack1 :");
    for(int i=0;i<5;i+=1)
    System.out.println(mystack1.pop());
    System.out.println("Stack in mystack2 :");
    for(int i=0;i<5;i+=1)
    System.out.println(mystack2.pop());

    ReplyDelete
  2. Solution:

    Source code:

    public class Stack
    {
    private static int MAX=10;
    private int a[]=new int[MAX];
    int top;
    Stack()
    {
    top=0;
    }
    public void push(int v)
    {
    if(top0)
    return a[--top];
    else
    {
    System.out.println("Underflow");
    return -1;
    }
    }
    }
    class StackArray
    {
    public static void main(String as[])
    {
    Stack s1=new Stack();
    s1.push(30);
    s1.push(40);
    s1.push(50);
    System.out.println(s1.pop());
    System.out.println(s1.pop());
    System.out.println(s1.pop());
    }
    }

    ReplyDelete
  3. The content is good and very informative and I personally thank you for sharing home repair and home improvement articles with us Ruby on Rails Developers

    ReplyDelete