Stack:: Algorithm For PUSH Operation

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

STACK:

A stack is an Abstract Data Type (ADT) which allows all data operations at one
end only; element which is placed (inserted or added) last, is accessed first. This
feature makes it LIFO (Last-in-first-out) data structure. In stack terminology,
insertion operation is called PUSH operation and removal operation is
called POP operation.

Algorithm for PUSH Operation


push(stack, value)
if stack is full
print “OVERFLOW”
return
endif
top ← top + 1
stack[top] ← value

Algorithm for Pop Operation

int pop(stack)
if stack is empty
print “UNDERFLOW”
return null
endif
data ← stack[top]
top ← top - 1
return data

// C program to implement stack operations: PUSH(insert


operation), POP(Delete operation) and Display stack.

/* Typical definition of stack data structure */

struct stack
{
int elements[MAXSIZE];
int top;
};
/* In main() */

int main ()
{
struct stack s; /* Typical declaration of stack */
s.top=-1; /* Top of stack s is initialized to -1 so that,
the first element can be pushed in 0th position
of the array*/
...
...
...
push(&s,value); /* Typical call to push function */
...
...
...
value = pop(&s); /* Typical call to pop function */
...
...
...
display(&s); /* Typical call to display function */
...
...
...
}

/* Function to add an element to the stack - push(&s,value)*/

void push(struct stack *s,int val)


{
if(s->top == (MAXSIZE - 1))
{
printf ("Stack is Full\n");
return;
}
else
{
s->top = s->top + 1;
s->elements[s->top] = val;
}
}
/*Function to delete an element from the stack - value=pop(&s)*/

int pop(struct stack *s)


{
int num;
if (s->top == - 1)
{
printf ("Stack is Empty\n");
return (s->top);
}
else
{
num = s->elements[s->top];
s->top = s->top - 1;
}
return(num);
}

/* Function to display the status of the stack - display(&s) */

void display(struct stack *s)


{
int i;
if (s->top == -1)
{
printf ("Stack is empty\n");
return;
}
else
{
printf ("\n Stack elements are: ");
for (i = s->top; i >= 0; i--)
{
printf ("%d\t", s->elements[i]);
}
}
}
QUEUE:

Queue is an ADT which is open at both its ends. One end is always used to insert
data (enqueue) and the other is used to remove data (dequeue). Queue
follows First-In-First-Out methodology, i.e., the data item stored first will be
accessed first.

Algorithm for enqueue operation

enqueue(queue, value)
if queue is full
print “OVERFLOW”
return
endif
rear ← rear + 1
queue[rear] ← value

Algorithm for dequeue operation

int dequeue(queue)
if queue is empty
print “UNDERFLOW”
return
end if
value = queue[front]
front ← front + 1
return value

You might also like