Thursday, January 20, 2011

22.Stack and Implementing Stack using Array


Introduce to stack data structure

Stack is a data structure which works based on principle of  last in first out (LIFO). In computing world, stack data structure can be applied in many applications such as parsing syntax of expressions, run-time memory management (used in Java virutal machine) and solving search problem.

Stack operations

Push and pop are the operations that are provided for insertion of an element into the stack and the removal of an element from the stack.

Array Implementation of a Stack using C

Here is source code of c which demonstrate stack data structure. You can also download them to your local PC and start practicing.


stack.c (0.6 KB)
stack implementation file: stack.c
stack.h (149 B)
Header file of stack: stack.h
teststack.c (0.6 KB)
Stack test file: teststack.c


Stack.h





void push(int *s,int* top, int element);
int pop(int *s,int *top);
int full(int *top,const int size);
int empty(int *top);
void init(int *top);

Stack.c




/*initialize stack pointer*/
 
void init(int *top)
{
               *top = 0;
}
 
 
/*push an element into stack 
precondition: the stack is not full */
 
void push(int *s,int* top, int element)
{
               s[(*top)++] = element;
}
 
 
 
/*      pop an element from stack
        precondition: stack is not empty */
 
int pop(int *s,int *top)
{
               return s[--(*top)];
}
 
 
 
/*      report stack is full nor not
        return 1 if stack is full, otherwise return 0 */
 
int full(int *top,const int size)
{
               return *top == size ? 1 : 0;
}
 
 
 
/*      report a stack is empty or not
        return 1 if the stack is empty, otherwise return 0 */
 
int empty(int *top)
{
               return *top == 0 ? 1 : 0;
}



teststack.c



#include <stdio.h>
#include <stdlib.h>
#include "stack.h"
 
#define size 3
 
void main()
{
               int top,element;
               int stack[size];
 
        // initialize stack
               init(&top);
               
        // push elements into stack
               while(!full(&top,size)){
                               element = rand();
                               printf("push element %d into stack\n",element);
                               push(stack,&top,element);
                               //press enter to push more
                               getchar();
 
               }
               printf("stack is full\n");
 
        // pop elements from stack
               while(!empty(&top)){
                  element = pop(stack,&top);
                  printf("pop element %d from stack\n",element);
           //press enter to pop more
                               getchar();
               }
               printf("stack is empty\n");
               
               getchar();
}

Dont Miss Another Post Connect With Us !

Enter your email address:

0 comments: