0% found this document useful (0 votes)
46 views

Lab 6

Here are the steps to add two large numbers 644 and 238 using two stacks: 1. Push the digits of 644 onto stack1 from right to left. So push 4, 4, 6. 2. Push the digits of 238 onto stack2 from right to left. So push 8, 3, 2. 3. Initialize a carry variable to 0. 4. Pop a digit from stack1 and stack2 and add them along with the carry. 5. If the sum is greater than 10, put the last digit of the sum in result stack and carry the remainder. 6. If the sum is less than 10, put the sum in result stack and make carry 0.

Uploaded by

Neha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views

Lab 6

Here are the steps to add two large numbers 644 and 238 using two stacks: 1. Push the digits of 644 onto stack1 from right to left. So push 4, 4, 6. 2. Push the digits of 238 onto stack2 from right to left. So push 8, 3, 2. 3. Initialize a carry variable to 0. 4. Pop a digit from stack1 and stack2 and add them along with the carry. 5. If the sum is greater than 10, put the last digit of the sum in result stack and carry the remainder. 6. If the sum is less than 10, put the sum in result stack and make carry 0.

Uploaded by

Neha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Week 6 and 7

Data Structures CS218


Instructor: Anam Qureshi
Topics till Mid Term #02
• Stack ADT and it’s applications
• Queue ADT and it’s applications
• Backtracking
– N-Queen problem
– Maze problem
• Elementary sorting algorithms
– Bubble, insertion, selection, and shell sort
Overview
• Introduction to Stack Data structure
• Static vs Dynamic stack
• Implementation details of stack
• Applications of stack
Introduction to the Stack
• Stack: a LIFO (last in, first out) data structure
• Examples:
– plates in a cafeteria serving area
– return addresses for function calls
Stack Basics
• Stack is usually implemented as a list, with
additions and removals taking place at one end of
the list
• The active end of the list implementing the stack
is the top of the stack
• Stack types:
– Static – fixed size, often implemented using an array
– Dynamic – size varies as needed, often implemented
using a linked list
Stack Operations and Functions
Operations:
– push: add a value at the top of the stack
– pop: remove a value from the top of the stack
Functions:
– isEmpty: true if the stack currently contains no
elements
– isFull: true if the stack is full; only useful for static
stacks
Push Operation
• Function: Adds newItem to the top of the
stack.
• Preconditions: Stack has been initialized
and is not full.
• Postconditions: newItem is at the top of
the stack.
Post Operation
• Function: Removes topItem from stack and
returns it in item.
• Preconditions: Stack has been initialized and is
not empty.
• Postconditions: Top element has been
removed from stack and item is a copy of the
removed element.
Stack Overflow and Underflow
Stack overflow
• The condition resulting from trying to push an
element onto a full stack.
if(!stack.IsFull())
stack.Push(item);
Stack underflow
• The condition resulting from trying to pop an
empty stack.
if(!stack.IsEmpty())
stack.Pop(item);
Static Stack Implementation
• Uses an array of a fixed size
• Bottom of stack is at index 0. A variable called top
tracks the current top of the stack
const int STACK_SIZE = 3;
char s[STACK_SIZE];
int top = 0;

top is where the next item will be added


Array Implementation Example
This stack has max capacity 3, initially top = 0 and stack
is empty.

K K
push('E'); push('K'); push('G');
E E E
top is 1 top is 2 top is 3
Stack Operations Example
After three pops, top == 0 and the stack is empty

K
pop(); pop(); pop();
(remove G) E (remove K) E (remove E)
Array Implementation
char s[STACK_SIZE];
int top=0;
To check if stack is empty:
bool isEmpty()
{
if (top == 0)
return true;
else return false;
}
char s[STACK_SIZE];
int top=0;
To check if stack is full:
bool isFull()
{
if (top == STACK_SIZE)
return true;
else return false;
}
To add an item to the stack
void push(char x)
{
if (isFull())
{error(); exit(1);}
// or could throw an
exception
s[top] = x;
top++;
}
To remove an item from the stack
void pop(char &x)
{
if (isEmpty())
{error(); exit(1);}
// or could throw an
exception
top--;
x = s[top];
}
Dynamic Stacks
• Implemented as a linked list
• Can grow and shrink as necessary
• Can't ever be full as long as memory is
available
Discussion
• How we will implement a dynamic stack using
linked list?
Application of Stacks
• Adding large numbers
• Infix to Postfix Conversion
• Evaluating Postfix notations
• Bracket Matching
• Tower of Hanoi
• Identifying Palindromes
• Searching in Graphs (Depth First Search)
• Undo Redo
• Backtracking
Adding large numbers
Infix to Postfix conversion
Rules of Operator Precedence
Infix to postfix conversion
• Rules to follow:
– Print operands as they arrive.
– If the stack is empty or contains a left parenthesis on top, push the incoming operator
onto the stack.
– If the incoming symbol is a left parenthesis, push it on the stack.
– 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.
– If the incoming symbol has higher precedence than the top of the stack, push it on the
stack.
– 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.
– 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.
– At the end of the expression, pop and print all operators on the stack. (No parentheses
should remain.)
Example Expression
Postfix Evaluation
• Rules to follow
• If the element is a number, push it into the stack
• If the element is a operator, pop operands for the operator
from stack. Evaluate the operator and push the result back
to the stack
Postfix Evaluation
Implementation Details
int prec(char c)
{
if(c == '^')
return 3;
else if(c == '*' || c == '/')
return 2;
else if(c == '+' || c == '-')
return 1;
else
return -1;
}
If the scanned character is operand
if((s[i] >= 'a' && s[i] <= 'z')||(s[i] >= 'A' && s[i] <= 'Z'))
ns+=s[i];

If the scanned character is ‘(’


if(s[i] == '(')
st.push('(');

If the scanned character is Operator


If(s[i] == Operator) then
while(!st.IsEmpty && prec(s[i]) <= prec(st.top())) do
char c = st.top();
st.pop();
ns += c;
end while
st.push(s[i]);
End if
If the scanned character is ‘)’
if(s[i] == ')') then
while(st.top() != '(') do
char c = st.top();
st.pop();
ns += c;
end while
if(st.top() == '(') then
char c = st.top();
st.pop();
end if
End if
Postfix Evaluation Algorithm
Algorithm postfix (String S)
Input: An expression
Output: Result of an expression
for each character ch in the postfix expression, do
if ch is an operator ⨀ , then
a := pop first element from stack
b := pop second element from the stack
res := b ⨀ a
push res into the stack
else if ch is an operand, then
add ch into the stack
end if
return element of stack top
End Procedure
Tasks to be implemented
Infix to postfix conversion
• Expression = (A+B^C)*D+E^5

• Step 1. Reverse the infix expression.


5^E+D*)C^B+A(
Step 2. Make Every ‘(‘ as ‘)’ and every ‘)’ as ‘(‘
5^E+D*(C^B+A)
Step 3. Convert expression to postfix form.
5E^DCB^A+*+
Step 4. Reverse the expression.
+*+A^BCD^E5
Question:
a/b-(c+d)-e --/ab+cde
Adding Large numbers using two
stacks

644
+238

You might also like