Wednesday 24 September 2014

Stacks as an Array

Stacks as an Array

First i am going to explain what is a 'stack', a stack is a Data structures with a predefined method of storing , retrieving and deleting the elements stored in it. 
Stacks follows Last In First Out(LIFO) mechanism, i.e., The element 'pushed' last into a stack will be the first one to be 'poped' out of the stack.
Push: The operation of inserting an element into the stack is familiarized as 'PUSH' in the world of stack.
Pop: The operation of removing an element from the stack is familiarized as 'POP'.

Below is a working C code for implementing stack as an array.
Stacks can also be implemented as linked list which i am going to discuss in my next post.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// STACK implemented as an array.
#include<stdio.h>
#define MAX 10
int a[MAX],top=-1;
void push(int n)
{
  printf("The element %d is PUSHED into the stack. :)\n",(a[++top]=n));
}
void pop()
{
  printf("the element %d is POPED. :)\n",a[top--]);
}
void display()
{
 int i;
 printf("The elements of stack are: ");
 for(i=0;i<=top;i++)
    printf("%d ",a[i]);
    printf("\n");
}
int main()
{
 int choice,n;
 while(1)
 {
  printf("Enter the operation to be done with STACK\n");
  printf("1.PUSH\n");
  printf("2.POP\n");
  printf("3.DISPLAY\n");
  printf("4.EXIT\n");
  scanf("%d",&choice);
  switch(choice)
  {
   case 1:
                if(top==MAX-1)
                {
                    printf("The stack is FULL. :(\n");
                    break;
                }
                printf("Enter the elemnt to be pushed\n");
                scanf("%d",&n);
    push(n);
    break;
   case 2:
                if(top==-1)
                {
                    printf("The stack is EMPTY. :(\n");
                    break;
                }
    pop();
    break;
   case 3:
                if(top==-1)
                {
                    printf("The stack is EMPTY. :(\n");
                    break;
                }
    display();
    break;
   case 4:
    return 0;
            default:
                printf("Please enter a valid option.\n");
                break;
  }
 }
}

No comments:

Post a Comment