0% found this document useful (0 votes)
8 views52 pages

C-Stacks and Queues

Uploaded by

nothingtodo6410
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views52 pages

C-Stacks and Queues

Uploaded by

nothingtodo6410
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 52

Programming and Data Structures

Debasis Samanta
Computer Science & Engineering
Indian Institute of Technology Kharagpur
Spring-2017
Lecture #13
Stack & Queue

CS 11001 : Programming and Data


2 Lecture #00: © DSamanta
Structures
Today’s discussion…

*Stack *Queue
* Basic principles * Basic principles
* Operation of stack * Operation of queue
* Stack using Array * Queue using Array
* Stack using Linked List * Queue using Linked List
* Applications of stack * Applications of queue

CS 11001 : Programming and Data


Structures
3 Lecture #00: © DSamanta
Stack

CS 11001 : Programming and Data


4 Lecture #00: © DSamanta
Structures
Basic Idea
•A stack is an Abstract Data Type (ADT), commonly used in most
programming languages. It is named stack as it behaves like a real-
world stack, for example – a deck of cards or a pile of plates, etc.

CS 11001 : Programming and Data


5 Lecture #00: © DSamanta
Structures
Stack Representation

• Can be implemented by means of Array, Structure, Pointers and


Linked List.
• Stack can either be a fixed size or dynamic.
CS 11001 : Programming and Data
6 Lecture #00: © DSamanta
Structures
push

pop

create
STACK
isempty

isfull

CS 11001 : Programming and Data


7 Lecture #00: © DSamanta
Structures
STACK: Last-In-First-Out (LIFO)
• void push (stack *s, int element);
/* Insert an element in the stack */
• int pop (stack *s);
/* Remove and return the top element */
• void create (stack *s);
/* Create a new stack */
• int isempty (stack *s);
/* Check if stack is empty */
• int isfull (stack *s);
/* Check if stack is full */

Assumption: stack contains integer elements!


CS 11001 : Programming and Data
8 Lecture #00: © DSamanta
Structures
Stack using Array

CS 11001 : Programming and Data


9 Lecture #00: © DSamanta
Structures
Push using Stack

PUSH

top
top

Autumn 2016 10 Autumn 2016


Pop using Stack

POP

top
top

Autumn 2016 11 Autumn 2016


Stack using Linked List

CS 11001 : Programming and Data


12 Lecture #00: © DSamanta
Structures
Push using Linked List

PUSH OPERATION

top

Autumn 2016 13 Autumn 2016


Pop using Linked List

POP OPERATION

top

Autumn 2016 14 Autumn 2016


Basic Idea
• In the array implementation, we would:
• Declare an array of fixed size (which determines the maximum
size of the stack).

• Keep a variable which always points to the “top” of the stack.


• Contains the array index of the “top” element.
• In the linked list implementation, we would:
• Maintain the stack as a linked list.
• A pointer variable top points to the start of the list.
• The first element of the linked list is considered as the stack top.
Autumn 2016 15 Autumn 2016
Declaration

#define MAXSIZE 100 struct lifo


{
struct lifo int value;
{ struct lifo *next;
int st[MAXSIZE]; };
int top; typedef struct lifo
}; stack;
typedef struct lifo
stack; stack *top;
stack s;

ARRAY LINKED LIST

CS 11001 : Programming and Data


16 Lecture #00: © DSamanta
Structures
Stack Creation

void create (stack *s) void create (stack **top)


{ {
s->top = -1; *top = NULL;
/* s->top points to /* top points to NULL,
last element indicating empty
pushed in; stack */
initially -1 */ }
}

ARRAY LINKED LIST

CS 11001 : Programming and Data


17 Lecture #00: © DSamanta
Structures
Pushing an element into stack

void push (stack *s, int element) void push (stack **top, int element)
{ {
stack *new;
if (s->top == (MAXSIZE-1))
{ new = (stack *)malloc (sizeof(stack));
printf (“\n Stack overflow”); if (new == NULL)
exit(-1); {
} printf (“\n Stack is full”);
exit(-1);
else
}
{
s->top++; new->value = element;
s->st[s->top] = element; new->next = *top;
} *top = new;
}
}

ARRAY LINKED LIST


CS 11001 : Programming and Data
18 Lecture #00: © DSamanta
Structures
Popping an element from stack

int pop (stack **top)


{
int pop (stack *s) int t;
{ stack *p;
if (s->top == -1) if (*top == NULL)
{ {
printf (“\n Stack underflow”); printf (“\n Stack is empty”);
exit(-1);
exit(-1); }
} else
else {
{ t = (*top)->value;
p = *top;
return (s->st[s->top--]); *top = (*top)->next;
} free (p);
} return t;
}
}

ARRAY LINKED LIST


CS 11001 : Programming and Data
19 Lecture #00: © DSamanta
Structures
Checking for stack empty

int isempty (stack *s) int isempty (stack *top)


{ {
if (s->top == -1) if (top == NULL)
return 1; return (1);
else else
return (0); return (0);
} }

ARRAY LINKED LIST

CS 11001 : Programming and Data


20 Lecture #00: © DSamanta
Structures
Checking for Stack Full

int isempty (stack *s) int isempty (stack *top)


{ {
if (s->top == -1) if (top == NULL)
return 1; return (1);
else else
return (0); return (0);
} }

ARRAY LINKED LIST

CS 11001 : Programming and Data


21 Lecture #00: © DSamanta
Structures
Example: A Stack using an Array
#include <stdio.h>
#define MAXSIZE 100
struct lifo
{
int st[MAXSIZE];
int top;
};
typedef struct lifo stack;
main() {
stack A, B;
create(&A);
create(&B);
push(&A,10);
push(&A,20);
push(&A,30);
push(&B,100);
push(&B,5);
printf (“%d %d”, pop(&A), pop(&B));
push (&A, pop(&B));
if (isempty(&B))
printf (“\n B is empty”);
return;
}

CS 11001 : Programming and Data


22 Lecture #00: © DSamanta
Structures
Example: A Stack using Linked List
#include <stdio.h>
struct lifo
{
int value;
struct lifo *next;
};
typedef struct lifo stack;
main() {
stack *A, *B;
create(&A);
create(&B);
push(&A,10);
push(&A,20);
push(&A,30);
push(&B,100);
push(&B,5);
printf (“%d %d”, pop(&A), pop(&B));
push (&A, pop(&B));
if (isempty(B))
printf (“\n B is empty”);
return;
}

CS 11001 : Programming and Data


23 Lecture #00: © DSamanta
Structures
Applications of Stacks
• Direct applications:
• Page-visited history in a Web browser
• Undo sequence in a text editor
• Chain of method calls in the Java Virtual Machine
• Validate XML

• Indirect applications:
• Auxiliary data structure for algorithms
• Component of other data structures

CS 11001 : Programming and Data


24 Lecture #00: © DSamanta
Structures
Infix and Postfix Notations
• Infix: operators placed between operands:
A+B*C
• Postfix: operands appear before their operators:-
ABC*+
• There are no precedence rules to learn in postfix notation, and
parentheses are never needed

CS 11001 : Programming and Data


25 Lecture #00: © DSamanta
Structures
Infix to Postfix
Infix Postfix
A+B AB+
A+B*C ABC*+
(A + B) * C AB+C*
A+B*C+D ABC*+D+
(A + B) * (C + D) AB+CD+*
A*B+C*D AB*CD*+

A+B* C  (A + (B * C))  (A + (B C *) )  A B C * +

A + B * C + D  ((A + (B * C)) + D )  ((A + (B C*) )+ D) 


((A B C *+) + D)  A B C * + D +
Autumn 2016 26
Infix to postfix conversion
• Use a stack for processing operators (push and pop operations).
• Scan the sequence of operators and operands from left to right and
perform one of the following:
• output the operand,
• push an operator of higher precedence,
• pop an operator and output, till the stack top contains operator of a lower
precedence and push the present operator.

CS 11001 : Programming and Data


27 Lecture #00: © DSamanta
Structures
The algorithm steps
1. Print operands as they arrive.
2. If the stack is empty or contains a left parenthesis on top, push the incoming operator onto
the stack.
3. If the incoming symbol is a left parenthesis, push it on the stack.
4. If the incoming symbol is a right parenthesis, pop the stack and print the operators until you
see a left parenthesis. Discard the pair of parentheses.
5. If the incoming symbol has higher precedence than the top of the stack, push it on the stack.
6. If the incoming symbol has equal precedence with the top of the stack, use association. If
the association is left to right, pop and print the top of the stack and then push the incoming
operator. If the association is right to left, push the incoming operator.
7. If the incoming symbol has lower precedence than the symbol on the top of the stack, pop
the stack and print the top operator. Then test the incoming operator against the new top of
stack.
8. At the end of the expression, pop and print all operators on the stack. (No parentheses
should remain.)
CS 11001 : Programming and Data
28 Lecture #00: © DSamanta
Structures
Infix to Postfix Conversion
Requires operator precedence information

Operands:
Add to postfix expression.

Close parenthesis:
pop stack symbols until an open parenthesis appears.

Operators:
Pop all stack symbols until a symbol of lower precedence appears. Then push
the operator.

End of input:
Pop all remaining stack symbols and add to the expression.

CS 11001 : Programming and Data


29 Lecture #00: © DSamanta
Structures
Infix to Postfix Rules
Current Operator Postfix string
Expression: symbol Stack
1 A A
A * (B + C * D) + E 2 * * A
3 ( *( A
becomes
4 B *( AB

ABC D * +* E+ 5 + *(+ AB
6 C *(+ ABC
7 * *(+* ABC
8 D *(+* ABCD
Postfix notation
9 ) * ABCD*+
is also called as
10 + + ABCD*+*
Reverse Polish
Notation (RPN) 11 E + ABCD*+*E
12 ABCD*+*E+

Autumn 2016 30
Symbol Precedence Rank(r)
(f)
+, - 1 -1
*, / 2 -1
a, b, c 3 1
# 0 -

* Precedence table for decision-


making by the machine

CS 11001 : Programming and Data


31 Lecture #00: © DSamanta
Structures
Initialization Crux
* 1. TOP 1 * while (f(NEXT)≤ f(S[TOP])
* S[TOP] ‘#’ * begin
* TEMPPOP(S, TOP)
* 2. POLISH ‘’ * POLISHPOLISH ● TEMP
* RANK  0 * RANKRANK +r(TEMP)
*
* 3. NEXT  If RANK < 1

NEXTCHAR(INFIX) * Write(‘INVALID’)
* Exit
* 4. while (NEXT ≠ ‘#’) * end
* begin * PUSH(S, TOP, NEXT)
* NEXT  NEXTCHAR(INFIX)
* end

Algo. for unparenthesized in-fix to post-fix


conversion

CS 11001 : Programming and Data


32 Lecture #00: © DSamanta
Structures
* 5. while(S[TOP] ≠ ‘#’) 6. if RANK = 1
* begin write(‘VALID’)
* TEMPPOP(S, TOP) else
* POLISHPOLISH ● TEMP
write(‘INVALID’)
* RANKRANK +r(TEMP) 7. STOP
* If RANK < 1
* Write(‘INVALID’)
* Exit
* end

*Algo. Contd…
CS 11001 : Programming and Data
33 Lecture #00: © DSamanta
Structures
Symbol Input Stack Rank (r)
precedenc precedenc
e e
(f) (g)
+, - 1 2 -1
*, / 3 4 -1
^ 6 5 -1
a, b, c 7 8 1
( 9 0 -
) 0 - -

* Precedence and Association table

CS 11001 : Programming and Data


34 Lecture #00: © DSamanta
Structures
Initialization Crux
* 1. TOP 1 * while (f(NEXT) < g(S[TOP])
* begin
* S[TOP] ‘(’ * TEMPPOP(S, TOP)
* 2. POLISH ‘’ * POLISHPOLISH ● TEMP
* RANKRANK +r(TEMP)
* RANK  0 * If RANK < 1

* 3. NEXT  * Write(‘INVALID’)

NEXTCHAR(INFIX) * Exit
end
* 4. while (NEXT ≠ ‘’) * if f(NEXT) ≠ g(S[TOP]

* begin * PUSH(S, TOP, NEXT)


Else POP(S, TOP)
* NEXT  NEXTCHAR(INFIX)
* end
* 5. If TOP ≠ 0 or RANK ≠ 1
* write(‘INVALID’)
Else write(‘VALID’)
6. STOP

* Algo. for parenthesized in-fix to post-fix


conversion
CS 11001 : Programming and Data
35 Lecture #00: © DSamanta
Structures
Queue

CS 11001 : Programming and Data


36 Lecture #00: © DSamanta
Structures
Basic Idea
• Queue is an abstract data structure, somewhat similar to Stacks. Unlike
stacks, a queue is open at both its ends. One end is always used to
insert data (enqueue) and the other is used to remove data (dequeue).

CS 11001 : Programming and Data


37 Lecture #00: © DSamanta
Structures
Queue Representation

• As in stacks, a queue can also be implemented using Arrays, Linked-


lists, Pointers and Structures.

CS 11001 : Programming and Data


38 Lecture #00: © DSamanta
Structures
enqueue

dequeue

create
QUEUE
isempty

size

CS 11001 : Programming and Data


39 Lecture #00: © DSamanta
Structures
QUEUE: First-In-First-Out (LIFO)
void enqueue (queue *q, int element);
/* Insert an element in the queue */
int dequeue (queue *q);
/* Remove an element from the queue */
queue *create();
/* Create a new queue */
int isempty (queue *q);
/* Check if queue is empty */
int size (queue *q);
/* Return the no. of elements in queue */

Assumption: queue contains integer elements!

Autumn 2016 Autumn 2016 40


Queue using Linked List

CS 11001 : Programming and Data


41 Lecture #00: © DSamanta
Structures
Basic Idea
• Basic idea:
• Create a linked list to which items would be added to one end and
deleted from the other end.
• Two pointers will be maintained:
• One pointing to the beginning of the list (point from where
elements will be deleted).
• Another pointing to the end of the list (point where new
elements will be inserted). Rear

Front DELETION INSERTION


Autumn 2016 42 Autumn 2016
Queue: Linked List Structure

ENQUEUE

front rear

Autumn 2016 43 Autumn 2016


Queue: Linked List Structure

DEQUEUE

front rear

Autumn 2016 44 Autumn 2016


Example :Queue using Linked List
struct qnode
{
int val;
struct qnode *next;
};

struct queue
{
struct qnode *qfront, *qrear;
};
typedef struct queue QUEUE;

void enqueue (QUEUE *q,int element)


{
struct qnode *q1;
q1=(struct qnode *)malloc(sizeof(struct qnode));
q1->val= element;
q1->next=q->qfront;
q->qfront=q1;
}

CS 11001 : Programming and Data


45 Lecture #00: © DSamanta
Structures
Example :Queue using Linked List
int size (queue *q)
{
queue *q1;
int count=0;
q1=q;
while(q1!=NULL) int dequeue (queue *q)
{ {
q1=q1->next; int val;
count++; queue *q1,*prev;
} q1=q;
return count; while(q1->next!=NULL)
} {
prev=q1;
q1=q1->next;
}
val=q1->val;
int peek (queue *q) prev->next=NULL;
{ free(q1);
queue *q1; return (val);
q1=q; }
while(q1->next!=NULL)
q1=q1->next;
return (q1->val);
}

CS 11001 : Programming and Data


46 Lecture #00: © DSamanta
Structures
Insert(Enqueue) Delete(Dequeue)
* Procedure QINS(Q, F, R, N, * Function QDEL(Q, F, R)
Y)
* 1. If F = 0
* 1.If R >= N * Write(‘Underflow’)
* Write(‘Overflow’) * Return(0)
* Return
* 2. Y  Q[F]
* 2. R  R + 1
* 3. If F = R
* 3. Q[R]  Y
*F  R 0
* 4. If F = 0
* F 1 * Else F  F + 1
5.Return * 4. Return(Y)

*Queue using
Array
CS 11001 : Programming and Data
47 Lecture #00: © DSamanta
Structures
Problem With Array Implementation
• The size of the queue depends on the number and order of enqueue
and dequeue.
• It may be situation where memory is available but enqueue is not
possible.
ENQUEUE DEQUEUE
Effective queuing storage area of array gets reduced.
0 N

front
front rearrear

Use of circular array indexing


Autumn 2016 48 Autumn 2016
Enqueue Dequeue
* Procedure CQINS(Q, F, R, N, Y) * Function CQDEL(Q, F, R)
* 1.If R = N * 1. If F = 0
* R1 * Write(‘Underflow’)
* Else R  R + 1 * Return(0)
* 2. If F = R * 2. Y  Q[F]
* Write(‘Overflow’) * 3. If F = R
* Return * F  R 0
* 3. Q[R]  Y * 4. If F = N
* 4. If F = 0 * F1

* F 1 * Else F  F + 1
5.Return * 5.Return(Y)

*Circular queue
CS 11001 : Programming and Data
49 Lecture #00: © DSamanta
Structures
* Circular Queue with another
implementation

CS 11001 : Programming and Data Stru 50 Lecture #00: © DSamanta


ctures
*Priority Queue
* Implemented using many arrays
* Implemented as min-heap
*Deque (Double-ended Queue)
*IR-Deque
*OR-Deque

*Types of Queues
CS 11001 : Programming and Data Stru 51 Lecture #00: © DSamanta
ctures
Applications of Queues
• Modelling and Simulation( a sub-field of Computer Science)
• Waiting lists
• Access to shared resources (e.g., printer)
• CPU Scheduling in Multiprogramming Environment(PQ)
• Three categories:
• Interrupts
• Interactive jobs
• Batch jobs

• Round-Robin Algorithm in OS (CQ)

CS 11001 : Programming and Data


52 Lecture #00: © DSamanta
Structures

You might also like