Stack and Queue: Programming & Data Structures
Stack and Queue: Programming & Data Structures
Pallab Dasgupta
Professor, Dept. of Computer
Sc. & Engg.,
Indian Institute of
Technology Kharagpur
Dept. of CSE, IIT KGP
Stack
In
Out
Stack: Definition
#define MAX_STACK_SIZE 100
typedef struct {
int key;
/* other fields */
} element;
typedef struct {
element list[MAX_STACK_SIZE];
int top;
} stack;
stack z;
z.top = -1;
/* Declaration */
/* Initialization */
Stack: Operations
void push( stack *s, element item )
{
if (s-> top >= MAX_STACK_SIZE -1) { stack_full( ); return; }
(s->top)++;
s->list[s->top] = item;
}
element pop( stack *s )
{
element item;
if (s->top = -1) return stack_empty( );
item = s->list[s->top];
(s->top)--; return item;
}
Examples:
()({}[({}{}())])
is proper
(){[]
is not proper
({)}
is not proper
)([]
is not proper
([]))
is not proper
Approach:
Whenever a right parenthesis is encountered, pop from stack and check if the
parentheses match.
Parenthesis matching
while (not end of string) do
{
a = get_next_token();
if (a is ( or { or [) push (a);
if (a is ) or } or ])
{
if (is_stack_empty( )) { print (Not well formed); exit(); }
x = pop();
if (a and x do not match) { print (Not well formed); exit(); }
}
}
if (not is_stack_empty( )) print (Not well formed);
Queue
Out
In
Queue: Definition
#define MAX_QUEUE_SIZE 100
typedef struct {
int key;
/* other fields */
} element;
typedef struct {
element list[MAX_QUEUE_SIZE];
int front;
int rear;
} queue;
queue z;
/*Declaration */
[4]
[5]
[2]
[1]
[0]
front=0
rear=0
[3]
[2] B
[1]
[6]
[6]
front=0[0]
[7]
After insertion
of A, B, C, D
[7]
Queue Empty
front=2
[2]
[3]
C
[4] rear = 4
D
[5]
[1]
[6]
[0]
[4] rear = 4
D
[5]
[7]
After deletion of
of A, B
[4]
[2]
[5]
[1]
[6]
[0]
front=0
rear=0
[7]
Queue Empty
rear = 3
[3]
front=4
[4]
[5]
[1]
[6]
[0]
Queue Empty Condition: front == rear
Queue Full Condition: front == (rear + 1) % MAX_QUEUE_SIZE
Dept. of CSE, IIT KGP
[7]
Queue Full
Queue: Operations
void addq( queue *q, element item )
{
q->rear = (q->rear + 1)% MAX_QUEUE_SIZE;
if (q->front == q->rear) { queue_full( ); return; }
q->list[q->rear] = item;
}
element deleteq( queue *q )
{
element item;
if (q->front == q->rear) return empty_queue( );
q-> front = (q-> front + 1)% MAX_QUEUE_SIZE;
return q->list[q->front] ;
}