Wednesday, 5 June 2013

Data Structures : Stacks explained and implementation using Arrays in C

When I think about stacks in real life I get a feel of these things ,
















Notice that is we pull or remove any element except the top , there are chances that the stack might collapse.
Hence , when we talk about stacks in data structures we only perform operation on the top element and nothing else. Here’s what a stack looks like ,




in other words stack is a data structure where operations take place at the same end.
Representing Stacks in C

A stack in C can be represented using arrays. It can be declared as structure containing two objects , an array to hold the elements of the stack and an integer to indicate the position of the current stack top within the array.



After this you need to declare a stack ‘ s ‘ by





Operations on Stack


There are two operations done on a stack :
PUSH - Insert a new element on top of the stack
POP - remove the top most element of the stack

represented by C functions  pop() and push(s) respectively , where s is the element to be pushed.


the above stack operations the done by calling the following set of functions in the given order ,
push(10);
push(20);
push(30);
pop();
pop();
pop();

C code for pop and push operations

Before implementing push and pop we define a simple function called empty  .



this function tells us if the stack is empty or not , or if we can pop further items from the stack or not . The situation in which no more elements are left to pop is called underflow.

pop operation




push operation









Applications of Stack


Stack is very common data structure used in programs. It has the following basic applications :

1. Solving an arithmetic expression like [{(a*b) + (c/d)}]
2. Expression Conversion , expressions like infix , postfix , prefix there mutual conversions
3. Simulating Recursion
4. Verifying an arithmetic expression
5. Parsing



We will discuss these application in the following posts . Hope this helps you get a brief overview of stack.

No comments:

Post a Comment