37
Stacks Linear list in which insertions and deletions can take place only at the top Last-In-First-Out (LIFO) list Insertion (push) Deletion (pop) 1

Data Structures: Stacks (Part 1)

Embed Size (px)

Citation preview

Page 1: Data Structures: Stacks (Part 1)

1

Stacks

Linear list in which insertions and deletions can take place only at the top

Last-In-First-Out (LIFO) list Insertion (push) Deletion (pop)

Page 2: Data Structures: Stacks (Part 1)

2

Stack Operations

6

5

4

3

2

1

0

top

6

5

4

3

2

1

0 2top

29

6

5

4

3

2

1

0 2

top

-23

29

6

5

4

3

2

1

0 2

top

-1

29

6

5

4

3

2

1

0 2

top

6

5

4

3

2

1

0 2top

Empty stack Push 2 Push 29 Push -23 Pop Pop

Page 3: Data Structures: Stacks (Part 1)

3

Stack Representation

Linear array or a linear linked list Representing a Stack using an Array Requirements

a variable, called top that holds the index of the top element

an array to hold the elements of the stack

Page 4: Data Structures: Stacks (Part 1)

4

Stack Representation

const int MAX = 10;class stack {

int top, list [MAX]; public:

stack() { top= –1;}void push (int);int pop(); int full(); int empty();void display();

};

Page 5: Data Structures: Stacks (Part 1)

5

Algorithm PUSH (S, MAX, TOP, X)

Inserts an element X onto a stack S of size MAX. TOP is a pointer to the top element of the stack.

1. [Check for stack overflow]If TOP MAXthen Write ('STACK OVERFLOW')

Return2. [Increment TOP]

TOP TOP + 13. [Insert element]

S [TOP] X4. [Finish]

Page 6: Data Structures: Stacks (Part 1)

6

Implementation of PUSH operation

int full(){if(top = = MAX–1) return 1;return 0;

}

void push (int num){list[++top] = num;

}

Page 7: Data Structures: Stacks (Part 1)

7

Algorithm POP (S, TOP)

Removes and returns the top element from a stack S. TOP is a pointer to the top element of the stack.

1. [Check for stack underflow]If TOP = –1

then Write('STACK UNDERFLOW') Return

2. [Decrement pointer] TOP TOP – 1

3. [Return former top element of stack and Finish]Return (S [TOP + 1])

Page 8: Data Structures: Stacks (Part 1)

8

Implementation of POP Operation

int empty(){if(top = = –1) {

cout<<"Stack underflow!"<<endl;

return 1; }return 0;

}

Page 9: Data Structures: Stacks (Part 1)

9

Implementation of POP Operation

int pop(){int num;num = list[top--];return (num);

}

Page 10: Data Structures: Stacks (Part 1)

10

Implementation of POP Operation

void display(){

if(!empty()) { cout<<"Index Element"<<endl;

for(int i=0; i<=top; i++) cout<<setw(3)<<i<<setw(10)<<list[i]<<endl; }

}

Page 11: Data Structures: Stacks (Part 1)

11

Implementation of POP Operation

void display(){

if(!empty()) { cout<<"Index Element"<<endl;

for(int i=0; i<=top; i++) cout<<setw(3)<<i<<setw(10)<<list[i]<<endl; }

}

Page 12: Data Structures: Stacks (Part 1)

12

Mathematical Expressions

Infix Notation Operand1 Operator Operand2

A+B Polish (Prefix) Notation

Operator Operand1 Operand2 +AB

Reverse Polish (Postfix or Suffix) Notation Operand1 Operand2 Operator

AB+

Page 13: Data Structures: Stacks (Part 1)

13

Infix to Prefix

(A – B / C) * (A * K – L)

(A – [/BC]) * ([* AK] – L)

[–A/BC] * [–*AKL]

*–A/BC–*AKL

Page 14: Data Structures: Stacks (Part 1)

14

Infix to Postfix

(A – B / C) * (A * K – L)

(A – [BC/]) * ([AK*] – L)

[ABC/–] * [AK*L –]

ABC/–AK*L–*

Page 15: Data Structures: Stacks (Part 1)

15

Advantages of Infix/Postfix Expressions

The order of operations determined by the positions of the operators and operands

Parentheses are not needed  

Page 16: Data Structures: Stacks (Part 1)

16

Evaluating Mathematical Expressions

Programs that perform some sort of translation often use stacks Example: The translation of an arithmetic

expression from infix notation to prefix or postfix notation.

Using infix notation, one cannot tell the order in which the operators should be applied by looking at the expression

Multiple operations use precedence rules The expression in the postfix notation is

much easy to evaluate

Page 17: Data Structures: Stacks (Part 1)

17

Evaluating Mathematical Expressions

As the operands appear before the operator, there is no need for operator precedence or for parentheses to group/order operations.

In order to evaluate a postfix expression It is scanned from left to right. Operands are pushed onto a stack When an operator is encountered

pop top one or two operands (depending on the operator)

perform the operation and place the result back on the stack.

At the end of the expression, the stack contains only one element (if expression is correct) and that is the resulting value of the expression

Page 18: Data Structures: Stacks (Part 1)

18

Algorithm InfixToPostfixInput: Infix string. Output: Postfix string.1. Examine the next element in the input.2. If it is an operand, output it, go to step 6.3. If it is an opening parenthesis, push it, go to step 6. 4. If it is an operator, then

a. If stack is empty, or the top of the stack is opening parenthesis, push the operator.

b. If the operator has higher priority than the top of stack, push the operator.

Else pop the operator from the stack and output it, repeat step 4a.

5. If it is a closing parenthesis, pop operators from the stack and output them until an opening parenthesis is encountered. Pop and discard the opening parenthesis.

6. If there is more input, go to step 1. Else pop the remaining operators to output

Page 19: Data Structures: Stacks (Part 1)

19

Convert 2*3/(2-1)+5*(4-1) into postfix form

Character Scanned

Stack Contents(Top on right) Postfix Expression

2 Empty 2* * 23 * 23/ / 23*( /( 23*2 /( 23*2- /(- 23*21 /(- 23*21) / 23*21-+ + 23*21-/5 + 23*21-/5* +* 23*21-/5( +*( 23*21-/54 +*( 23*21-/54- +*(- 23*21-/541 +*(- 23*21-/541) +* 23*21-/541-  Empty 23*21-/541-*+

Page 20: Data Structures: Stacks (Part 1)

20

Algorithm InfixToPrefix1. Initialize an empty stack and scan the input string from right to

left.2. Examine the next element in the input.3. If it is an operand, add it to output string, go to step 7.4. If it is a closing parenthesis, push it, go to step 7.5. If it is an operator, then

a) If stack is empty, or if the top of stack is a closing parenthesis, push the operator.

b) If the operator has same or higher priority than the top of stack, push the operator.

Else pop the operator from the stack and add it to output string, go to

step 5a.6. If it is an opening parenthesis, pop operators from stack and add

them to output string until a closing parenthesis is encountered. Pop and discard the closing parenthesis.

7. If there is more input, go to step 2. Else pop the remaining operators and add them to output string.8. Reverse the output string.

Page 21: Data Structures: Stacks (Part 1)

21

Convert 2*3/(2-1)+5*(4-1) into prefix formReversed Expression: )1-4(*5+)1-2(/3*2

Char Scanned Stack Contents(Top on right) Prefix Expression(right to left)

) )  1 ) 1- )- 14 )- 14( Empty 14-* * 14-5 * 14-5+ + 14-5*) +) 14-5*1 +) 14-5*1- +)- 14-5*12 +)- 14-5*12( + 14-5*12-/ +/ 14-5*12-3 +/ 14-5*12-3* +/* 14-5*12-32 +/* 14-5*12-32  Empty 14-5*12-32*/+

Page 22: Data Structures: Stacks (Part 1)

22

Applications of Stacks Function Calls

Stacks are used to pass parameters between functions. On call to a function, the parameters and local variables are stored on a stack.

Implementing Recursion There are many problems whose algorithmic

description is best described in a recursive manner. Many high-level programming languages provide support for recursion use stack.

Checking the validity or correctness of mathematical expressions.

Conversion and evaluation of mathematical expressions.

Page 23: Data Structures: Stacks (Part 1)

23

Queues

An ordered collection of items

deletion at one end (front)

insertion at the other end (rear)

Elements are processed in the same order as they join the queue

first-in, first-out (FIFO)

first-come, first-served (FCFS)

Page 24: Data Structures: Stacks (Part 1)

24

Queue

X X X X X X X X

Front Rear

Deletion Insertion

Page 25: Data Structures: Stacks (Part 1)

25

Algorithm QINSERT (Q, N, F, R, X)

1. [Check for Queue Overflow]If R N then

Write ('OVERFLOW')Return

2. [Increment rear pointer]R R + 1

3. [Insert element]Q(R) X

4. [Is front pointer properly set?]If F = 0 then

F 15. [Finish]

Return

Page 26: Data Structures: Stacks (Part 1)

26

Algorithm QDELETE (Q, N, F, R)

1. [Check for Queue Underflow] If F = 0 then

Write ('UNDERFLOW')Return (0) (0 denotes an empty

queue)2. [Delete element]

Y Q(F)3. [Queue empty?]

If F = R thenF R 0

else F F + 1

4. [Return element and Finish]Return (Y)

Page 27: Data Structures: Stacks (Part 1)

Queue Operations

27

R

Empty A Insert A

F R

A B Insert B

F R

A B C Insert C

F R

B C Delete A

F R

C Delete B

F R

C D Insert D

F R

C D Insert E

F R (Overflow)

(i)

(iii) (iv)

(v) (vi)

(vii) (viii)

(ii)F

Page 28: Data Structures: Stacks (Part 1)

28

Circular Queue

D

C

Q[2]

Q[1]Q[n]

F

R

. . .

Q[n-1]

Q[n-2]

Page 29: Data Structures: Stacks (Part 1)

29

Algorithm CQINSERT (Q, N, F, R, X)

1. [Reset rear pointer]If R = N then

R 1else

R R + 12. [Overflow?]

If F = R thenWrite ('OVERFLOW') and Return

3. [Insert element]Q[R] X

4. [Is front pointer properly set?] If F = 0 then

F 15. [Finish]

Return

Page 30: Data Structures: Stacks (Part 1)

30

Algorithm CQDELETE (Q, N, F, R)

This algorithm deletes and returns the last element of the queue. Y is a temporary variable.

1. [Underflow?] If F = 0 then Write('UNDERFLOW'),

Return (0)2. [Delete element] Y Q[F]3. [Queue empty?] If F = R then F R

0 4.[Increment front pointer] If F = N then F 1 else F F +

1 5. [Return element and Finish] Return (Y)

Page 31: Data Structures: Stacks (Part 1)

31

Priority Queues

A queue in which we are able to insert items or remove items from any position based on some property (such as priority of the task to be processed) is often referred to as a priority queue.

Priorities of 1, 2, and 3 are attached to jobs of type real-time, on-line, and batch, respectively.

If a job is initiated with priority i, it is inserted immediately at the end of the list of other jobs with priority i, for i = 1, 2, or 3. 

Page 32: Data Structures: Stacks (Part 1)

32

Priority Queues - Types

Ascending / descending priority In an ascending priority queue, elements

are processed in the increasing order of their priority values.

In a descending priority queue, elements are processed in the decreasing order of their priority values.

In both the types, elements with same priority are processed according to the order in which they are inserted.

Page 33: Data Structures: Stacks (Part 1)

33

Applications of Queues

In simulations and operating systems. Operating systems often maintain a queue of

processes that are ready to execute or that are waiting for a particular event to occur.

“holding area” for messages between two processes, two programs, or even two systems is (called a “buffer”) often implemented as a queue.

A file/print server in a computer network handles file access request from many clients throughout the network.

Servers have a limited capacity to service request from clients. When that capacity is exceeded, client requests wait in queues.

Page 34: Data Structures: Stacks (Part 1)

34

Lists

A homogeneous collection of elements, with a linear relationship between the elements.

Lists can be unordered - their elements can be placed without a particular order, or ordered – their elements are placed in a particular order.

Stacks and queues are lists whose elements are ordered based on the sequence in which they have been inserted.

The lists can also be ordered by the value.

Page 35: Data Structures: Stacks (Part 1)

35

Lists

Ex. A list ordered alphabetically, and a list ordered numerically (in ascending or descending order).

Value-ordered lists or sorted lists. On one of the fields in the record, the record

key. Ex. A list of students in a class can be

ordered alphabetically by name, or numerically by roll number.

Key-ordered-lists. Lists can be implemented using

Linear Arrays or Linked Lists

Page 36: Data Structures: Stacks (Part 1)

36

Linked Lists

A linked list is a linear collection of similar elements, called nodes.

The linear order is given by pointers. Each node is divided into two or more

parts. A linked list can be one of the following

types: Linear linked list, or singly linked list, or one-

way list Doubly linked list or two-way list Circular linked list

Page 37: Data Structures: Stacks (Part 1)

37

Linear Linked Lists

info NextPointer

4148 4156 4164 4172

head

X

Structure of a node

A Linear Linked List with four nodes