0% found this document useful (0 votes)
3 views14 pages

Stack Data Structure

Jjk ch 3

Uploaded by

jannatjoya466
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
3 views14 pages

Stack Data Structure

Jjk ch 3

Uploaded by

jannatjoya466
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 14

Stack Data Structure

Stack is a linear data structure that follows a particular order in which


the operations are performed. The order may be LIFO(Last In First Out)
or FILO(First In Last Out).
It contains only one pointer top pointer pointing to the topmost element
of the stack. Whenever an element is added in the stack, it is added on
the top of the stack, and the element can be deleted only from the stack.
In other words, a stack can be defined as a container in which
insertion and deletion can be d done
one from the one end known as the
top of the stack.

Working of Stack
Stack works on the LIFO pattern. As we can observe in the below figure
there are five memory blocks in the stack; therefore, the size of the stack
is 5.
Suppose we want to store the elements in a stack and let's assume that
stack is empty. We have taken the stack of size 5 as shown below in
which we are pushing the elements one by one until the stack becomes
full.
Top =0 Top=1 Top=2

Top=33 Top
Top=4
Since our stack is full as the size of the stack is 5. In the above cases, we
can observe that it goes from the top to the bottom when we were
entering the new element in the stack. The stack gets filled up from the
bottom to the top.
When we perform the delete operation on the stack, there is only one
way for entry and exit as the other end is closed. It follows the LIFO
pattern, which means that the value entered first will be removed last. In
the above case,
se, the value 10 is entered first, so it will be removed only
after the deletion of all the other elements.

Applications of Stack

1. In a stack, only limited operations are performed because it is


restricted data structure. The elements are deleted from the stack
in the reverse order.

Following are the applications of stack:

1. Expression Evaluation
2. Expression Conversion
i. Infix to Postfix
ii. Infix to Prefix
iii. Postfix to Infix
3.Backtracking
4.Delimiter Checking
5.Reverse a Data
6.Processing Function Calls

1. Evaluation of Arithmetic Expressions


A stack is a very effective data structure for evaluating arithmetic expressions
in programming languages. An arithmetic expression consists of operands and
operators.

In addition to operands and operators, the arithmetic expression may also


include parenthesis like "left parenthesis" and "right parenthesis".

Example: A + (B - C)

To evaluate the expressions, one needs to be aware of the standard


precedence rules for arithmetic expression. The precedence rules for the five
basic arithmetic operators are:

Operators Associativity Precedence

^ exponentiation Right to left Highest followed by *Multiplication


and /division

*Multiplication, Left to right Highest followed by + addition and -


/division subtraction

+ addition, - Left to right lowest


subtraction

Evaluation of Arithmetic Expression requires two steps:


o First, convert the given expression into special notation.
o Evaluate the expression in this new notation.
Notations for Arithmetic Expression
There are three notations to represent an arithmetic expression:

o Infix Notation
o Prefix Notation
o Postfix Notation

Infix Notation

The infix notation is a convenient way of writing an expression in which each


operator is placed between the operands. Infix expressions can be
parenthesized or unparenthesized depending upon the problem requirement.

Example: A + B, (C - D) etc.

All these expressions are in infix notation because the operator comes
between the operands.

Prefix Notation

The prefix notation places the operator before the operands. This notation was
introduced by the Polish mathematician and hence often referred to as polish
notation.

Example: + A B, -CD etc.

All these expressions are in prefix notation because the operator comes before
the operands.

Postfix Notation

The postfix notation places the operator after the operands. This notation is
just the reverse of Polish notation and also known as Reverse Polish notation.

Example: AB +, CD+, etc.

All these expressions are in postfix notation because the operator comes after
the operands.
Conversion of Arithmetic Expression into various Notations:

Infix Notation Prefix Notation Postfix Notation

A*B *AB AB*

(A+B)/C /+ ABC AB+C/

(A*B) + (D-C) +*AB - DC AB*DC-+

Evaluating Postfix expression:

Stack is the ideal data structure to evaluate the postfix expression because the
top element is always the most recent operand. The next element on the Stack
is the second most recent operand to be operated on.

Before evaluating the postfix expression, the following conditions must be


checked. If any one of the conditions fails, the postfix expression is invalid.

o When an operator encounters the scanning process, the Stack must


contain a pair of operands or intermediate results previously calculated.
o When an expression has been completely evaluated, the Stack must
contain exactly one value.

Example:

Now let us consider the following infix expression 2 * (4+3) - 5.

Its equivalent postfix expression is 2 4 3 + * 5.

The following step illustrates how this postfix expression is evaluated.


2. Backtracking
Backtracking is another application of Stack. It is a recursive algorithm that is
used for solving the optimization problem.

3. Delimiter Checking
The common application of Stack is delimiter checking, i.e., parsing that
involves analyzing a source program syntactically. It is also called parenthesis
checking. When the compiler translates a source program written in some
programming language such as C, C++ to a machine language, it parses the
program into multiple individual parts such as variable names, keywords, etc.
By scanning from left to right. The main problem encountered while
translating is the unmatched delimiters. We make use of different types of
delimiters include the parenthesis checking (,), curly braces {,} and square
brackets [,], and common delimiters /* and */. Every opening delimiter must
match a closing delimiter, i.e., every opening parenthesis should be followed
by a matching closing parenthesis. Also, the delimiter can be nested. The
opening delimiter that occurs later in the source program should be closed
before those occurring earlier.
Valid Delimiter Invalid Delimiter

While ( i > 0) While ( i >

/* Data Structure */ /* Data Structure

{ ( a + b) - c } { ( a + b) - c

To perform a delimiter checking, the compiler makes use of a stack. When a


compiler translates a source program, it reads the characters one at a time,
and if it finds an opening delimiter it places it on a stack. When a closing
delimiter is found, it pops up the opening delimiter from the top of the Stack
and matches it with the closing delimiter.

On matching, the following cases may arise.

o If the delimiters are of the same type, then the match is considered
successful, and the process continues.
o If the delimiters are not of the same type, then the syntax error is
reported.

When the end of the program is reached, and the Stack is empty, then the
processing of the source program stops.

Example: To explain this concept, let's consider the following expression.

[{a -b) * (c -d)}/f]


4. Reverse a Data:
To reverse a given set of data, we need to reorder the data so that the first
and last elements are exchanged, the second and second last element are
exchanged, and so on for all other elements.

Example: Suppose we have a string Welcome, then on reversing it would be


Emoclew.

There are different reversing applications:

o Reversing a string
o Converting Decimal to Binary

Reverse a String
A Stack can be used to reverse the characters of a string. This can be achieved
by simply pushing one by one each character onto the Stack, which later can
be popped from the Stack one by one. Because of the last in first
out propertyty of the Stack, the first character of the Stack is on the bottom of
the Stack and the last character of the String is on the Top of the Stack and
after performing the pop operation in the Stack, the Stack returns the String in
Reverse order.

Converting Decimal to Binary:


Although decimal numbers are used in most business applications, some
scientific and technical applications require numbers in either binary, octal, or
hexadecimal. A stack can be used to convert a number from decimal to
binary/octal/hexadecimal
xadecimal form. For converting any decimal number to a binary
number, we repeatedly divide the decimal number by two and push the
remainder of each division onto the Stack until the number is reduced to 0.
Then we pop the whole Stack and the result obtaine
obtained
d is the binary equivalent
of the given decimal number.

Example: Converting 14 number Decimal to Binary:


In the above example, on dividing 14 by 2, we get seven as a quotient and one
as the reminder, which is pushed on the Stack. On again dividing seven by 2,
we get three as quotient and 1 as the reminder, which is again pushed onto
the Stack. This process continues until the given number is not reduced to 0.
When we pop off the Stack completely, we get the equivalent binary
number 1110.

5. Processing Fun
Function Calls:
Stack plays an important role in programs that call several functions in
succession. Suppose we have a program containing three functions: A, B, and
C. function A invokes function B, which invokes the function C.
When we invoke function A, which contains a call to function B, then its
processing will not be completed until function B has completed its execution
and returned. Similarly for function B and C. So we observe that function A will
only be completed after function B is completed and function B will only be
completed after function C is completed. Therefore, function A is first to be
started and last to be completed. To conclude, the above function activity
matches the last in first out behavior and can easily be handled using Stack.

Expression Representation
There are three popular methods used for representation of an
expression:

Infix A+B Operator between operands.

Prefix + AB Operator before operands.

Postfix AB + Operator after operands.

1. Conversion of Infix to Postfix


Algorithm for Infix to Postfix

Step 1: Consider the next element in the input.

Step 2: If it is operand, display it.

Step 3: If it is opening parenthesis, insert it on stack.

Step 4: If it is an operator, then

 If stack is empty, insert operator on stack.


 If the top of stack is opening parenthesis, insert the operator on stack
 If it has higher priority than the top of stack, insert the operator on
stack.
 Else, delete the operator from the stack and display it, repeat Step 4.
Step 5: If it is a closing parenthesis, delete the operator from stack and
display them until an opening parenthesis is encountered. Delete and
discard the opening parenthesis.

Step 6: If there is more input, go to Step 1.

Step 7: If there is no more input, delete the remaining operators to


output.

Example: Suppose we are converting 3*3/(4-1)+6*2 expression into


postfix form.

Following table shows the evaluation of Infix to Postfix:

Expression Stack Output

3 Empty 3

* * 3

3 * 33

/ / 33*

( /( 33*

4 /( 33*4

- /(- 33*4

1 /(- 33*41

) - 33*41-

+ + 33*41-/
6 + 33*41-/6

* +* 33*41-/62

2 +* 33*41-/62

Empty 33*41-/62*+

So, the Postfix Expression is 33*41-/62*+

Implementation:
There are two ways to implement a stack:
 Using array
 Using linked list

Push Operation
The process of putting a new data element onto stack is known as a Push
Operation. Push operation involves a series of steps −
 Step 1 − Checks if the stack is full.
 Step 2 − If the stack is full, then Display message “stack is
OVERFULL” and exit.
 Step 3 − If the stack is not full, increments top to point next empty
space.
 Step 4 − Adds data element to the stack location, where top is pointing.
 Step 5 − Returns success.

Algorithm: PUSH (Insert) Operation in Stack


Step 1: If Top=Max-1

Print “ Overflow : Stack is full” and Exit

End If

Step 2: Top=Top+1
Step 3: Stack [ TOP ]=Element

Step 4: End

Algorithm: POP (Delete) Operation in Stack


Step 1: If TOP=-1

Print “Underflow: Stack is empty” and Exit

End if

Step 2: Set Del_element =Stack [ Top ]

Step 3: Top=Top-1

Step 4: Del_Element

Step 5: End

You might also like