Thursday, January 14, 2010

Stack implementation using linked list

We will be understanding the stack implementation using linked list. So, please understand the link list before proceeding.

Lets understand how we can implement the different operation using linked list.

CPP implementation
Here is how we use linked list to implement stack in cpp:
#include <iostream>

using namespace std;

struct node
{
       int info;
       struct node *next;

};

struct node *top;

int empty()
{
    return((top == NULL)? 1:0);
}

void push(int n)
{
     struct node *p;
     p=new node;
     if(p!=NULL)
     {
                p->info=n;
                p->next=top;
                top=p;
     }
     else
         cout<<"Not inserted,No memory available";
}

int pop()
{
    struct node *temp;
    int x;
    x=top->info;
    temp=top;
    top=top->next;
    free(temp);
    return(x);
}

void print()
{

     int i =0;
     struct node * temp;
     temp = top;
     cout<<"\n\t\t";
     if(temp==NULL)
          cout<<"\n\t\tNo elements\n";
     else
     {
         while(temp!=NULL)
         {
              int info = temp->info;
              cout<info<<"  ";
              temp=temp->next;
         }

         cout<<"End of List<<"\n";
      }
}


Implementation in java

Here is the implementation in java
class ListNode<E>
{
    E data;
    ListNode<E> next;
}
public class Stack<E>
{
    private ListNode<E> m_head;
 
    public Stack () {
        m_head = null;
    }
 
    public void push (E n) {
        ListNode<E> tmp = getNewNode();
        tmp.data = n;
 
        ListNode<E> oHead = m_head;
        m_head = tmp;
        m_head.next = oHead;
    }
 
    public void pop () {
        if (isEmpty()) throw new NoSuchElementException("Stack is Empty");
        m_head = m_head.next;
    }
 
    public E top () {
        return m_head.data;
    }
 
    public boolean isEmpty () {
        return m_head == null;
    }
 
    private ListNode<E> getNewNode () {
        return new ListNode<E>();
    }
}

Now testing the class above
import junit.framework.Assert;
 
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
 
public class StackTest
{
    private String[] elems = new String[] { "A", "B", "C" };
    private Stack<String> stack = new Stack<String>();
 
    @Before
    public void setup () {
        for (String str : elems)
        {
            stack.push(str);
        }
    }
 
    @After
    public void destroy () {
        while (stack.isEmpty() == false)
        {
            stack.pop();
        }
    }
 
    @Test
    public void testTop () {
        Assert.assertEquals(stack.top(), "C");
    }
 
    @Test
    public void testPush () {
        Assert.assertEquals(stack.top(), "C");
        stack.pop();
        Assert.assertEquals(stack.top(), "B");
        stack.pop();
        Assert.assertEquals(stack.top(), "A");
    }
}
Please let us know the feedback.

0 comments:

Post a Comment