Recent Posts

Thứ Hai, 15 tháng 8, 2011

Stack Data Structure


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.h
1void push(int *s,int* top, int element);
2int pop(int *s,int *top);
3int full(int *top,const int size);
4int empty(int *top);
5void init(int *top);
Stack.c
01/*
02    initialize stack pointer
03*/
04void init(int *top)
05{
06    *top = 0;
07}
08
09/*
10    push an element into stack
11    precondition: the stack is not full
12*/
13void push(int *s,int* top, int element)
14{
15    s[(*top)++] = element;
16}
17/*
18    pop an element from stack
19    precondition: stack is not empty
20*/
21int pop(int *s,int *top)
22{
23    return s[--(*top)];
24}
25/*
26    report stack is full nor not
27    return 1 if stack is full, otherwise return 0
28*/
29int full(int *top,const int size)
30{
31    return *top == size ? 1 : 0;
32}
33/*
34    report a stack is empty or not
35    return 1 if the stack is empty, otherwise return 0
36*/
37int empty(int *top)
38{
39    return *top == 0 ? 1 : 0;
40}
teststack.c


Không có nhận xét nào:

Đăng nhận xét