SlideShare uma empresa Scribd logo
1 de 58
Stacks
CS 308 – Data Structures
What is a stack?
• It is an ordered group of homogeneous items of elements.
• Elements are added to and removed from the top of the
stack (the most recently added items are at the top of the
stack).
• The last element to be added is the first to be removed
(LIFO: Last In, First Out).
Stack
• Stack operations may involve initializing the
stack, using it and then de-initializing it. Apart
from these basic stuffs, a stack is used for the
following two primary operations −
•  push() − Pushing (storing) an element on the
stack.
•  pop() − Removing (accessing) an element from
the stack.
• When data is PUSHed onto stack.
• To use a stack efficiently, we need to check the
status of stack as well. For the same
•  peek() − get the top data element of the stack,
without removing it.
•  isFull() − check if stack is full.
•  isEmpty() − check if stack is empty.
• At all times, we maintain a pointer to the last
PUSHed data on the stack. As this pointer
• always represents the top of the stack, hence
named top. The top pointer provides top
• value of the stack without actually removing it.
peek()
• Implementation of peek() function in C
programming language −
• int peek() {
• return stack[top];
• }
isfull()
• bool isfull() {
• if(top == MAXSIZE)
• return true;
• else
• return false;
• }
isempty()
• Implementation of isempty() function in C programming
language is slightly different. We initialize top at -1, as the
index in array starts from 0. So we check if the top is
below zero or -1 to determine if the stack is empty. Here's
the code −
• bool isempty() {
• if(top == -1)
• return true;
• else
• return false;
• }
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, produces an error
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.
Impelementation in C
• void push(int data) {
• if(!isFull()) {
• top = top + 1;
• stack[top] = data;
• }else {
• printf("Could not insert data, Stack is
full.n");
• }
• }
Pop Operation
• Accessing the content while removing it from the
stack, is known as a Pop Operation. In an array
implementation of pop() operation, the data
element is not actually removed, instead top is
decremented to a lower position in the stack to
point to the next value. But in linked-list
implementation, pop() actually removes data
element and deallocates memory space.
• Step 1 − Checks if the stack is empty.
• Step 2 − If the stack is empty, produces an error
and exit.
• Step 3 − If the stack is not empty, accesses the data
element at which top is
• pointing.
• Step 4 − Decreases the value of top by 1.
• Step 5 − Returns success.
Impelementation in C
int pop(int data) {
if(!isempty()) {
data = stack[top];
top = top - 1;
return data;
}else {
printf("Could not retrieve data, Stack is
empty.n");
}
}
Stack Implementation
#include <stdio.h>
int MAXSIZE = 8;
int stack[8];
int top = -1;
int isempty() {
if(top == -1)
return 1;
else
return 0;
}
int isfull() {
if(top == MAXSIZE)
return 1;
else
return 0;
}
Stack Implementation (cont.)
• int peek() {
• return stack[top];
• }
• int pop() {
• int data;
• if(!isempty()) {
• data = stack[top];
• top = top - 1;
• return data;
• }else {
• printf("Could not retrieve data, Stack is empty.n");
• }
Stack Implementation (cont.)
int push(int data) {
if(!isfull()) {
top = top + 1;
stack[top] = data;
}else {
printf("Could not insert data, Stack is full.n");
}
}
int main() {
// push items on to the stack
push(3);
push(5);
push(9);
push(1);
push(12);
push(15);
printf("Element at top of the stack: %dn" ,peek());
printf("Elements: n");
//print stack data
while(!isempty()) {
int data = pop();
printf("%dn",data);
}
printf("Stack full: %sn" , isfull()?"true":"false");
printf("Stack empty: %sn" ,
isempty()?"true":"false");
return 0;
}
Output
• Element at top of the stack: 15
• Elements:
• 15
• 12
• 1
• 9
• 5
• 3
• Stack full: false
• Stack empty: true
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);
Expression Parsing
• The way to write arithmetic expression is known
as a notation. An arithmetic expression
• can be written in three different but equivalent
notations, i.e., without changing the
• essence or output of an expression. These
notations are −
•  Infix Notation
•  Prefix (Polish) Notation
•  Postfix (Reverse-Polish) Notation
Example: postfix expressions
• Postfix notation is another way of writing arithmetic
expressions.
• In postfix notation, the operator is written after the
two operands.
infix: 2+5 postfix: 2 5 +
• Expressions are evaluated from left to right.
• Precedence rules and parentheses are never needed!!
Example: postfix expressions
(cont.)
Postfix expressions:
Algorithm using stacks (cont.)
Postfix expressions:
Algorithm using stacks
WHILE more input items exist
Get an item
IF item is an operand
stack.Push(item)
ELSE
stack.Pop(operand2)
stack.Pop(operand1)
Compute result
stack.Push(result)
stack.Pop(result)
Write the body for a function that replaces each copy of an
item in a stack with another item. Use the following
specification. (this function is a client program).
ReplaceItem(StackType& stack, ItemType oldItem,
ItemType newItem)
Function: Replaces all occurrences of oldItem with
newItem.
Precondition: stack has been initialized.
Postconditions: Each occurrence of oldItem in stack has
been replaced by newItem.
(You may use any of the member functions of the
StackType, but you may not assume any knowledge of
how the stack is implemented).
{
ItemType item;
StackType tempStack;
while (!Stack.IsEmpty()) {
Stack.Pop(item);
if (item==oldItem)
tempStack.Push(newItem);
else
tempStack.Push(item);
}
while (!tempStack.IsEmpty()) {
tempStack.Pop(item);
Stack.Push(item);
}
}
1
2
3
3
5
1
1
5
3
Stack
Stack
tempStack
oldItem = 2
newItem = 5
Exercises
• 1, 3-7, 14, 12, 15, 18, 19
Infix to Postfix
• Infix notation is easier for humans to read
and understand whereas for electronic
machines
• like computers, postfix is the best form of
expression to parse. We shall see here a
program
• to convert and evaluate infix notation to
postfix notation
−
Program
• #include<stdio.h>
• #include<string.h>
• //char stack
• char stack[25];
• int top = -1;
• void push(char item) {
• stack[++top] = item;
• }
• char pop() {
• return stack[top--];
• }
• //returns precedence of operators
• int precedence(char symbol) {
• switch(symbol) {
• case '+':
• case '-':
• return 2;
• break;
• case '*':
• case '/':
• return 3;
• break;
• case '^':
• return 4;
• break;
• case '(':
• case ')':
• case '#':
• return 1;
• break;
• }
• }
//check whether the symbol is operator?
• int isOperator(char symbol) {
• switch(symbol) {
• case '+':
• case '-':
• case '*':
• case '/':
• case '^':
• case '(':
• case ')':
• return 1;
• break;
• default:
• return 0;
}
//converts infix expression to
postfix
• void convert(char infix[],char postfix[]) {
• int i,symbol,j = 0;
• stack[++top] = '#';
• for(i = 0;i<strlen(infix);i++) {
• symbol = infix[i];
• if(isOperator(symbol) == 0) {
• postfix[j] = symbol;
• j++;
• } else {
• if(symbol == '(') {
• push(symbol);
• }else {
• if(symbol == ')') {
• while(stack[top] != '(') {
• postfix[j] = pop();
• j++;
• }
• pop();//pop out (.
• } else {
• if(precedence(symbol)>precedence(stack[top])) {
• push(symbol);
• }else {
• while(precedence(symbol)<=precedence(stack[top
])) {
• postfix[j] = pop();
• j++;
Algorithm
• An algorithm is a sequence of finite number of steps to
solve a specific problem.
• A algorithm can be defined as well –defined step by step
computational procedure which takes set of values as
input and produce set of values as output.
• A finite set of instruction that followed to accomplish a
particular task.
38
Algorithm Terminology : format conventions
1. Name of algorithm:
every algorithm is given an identifying name. the
name written in capital letter.
2. Introductory comments:
the algorithms name is followed by a brief
introduction regarding the task the algorithm will
perform. in addition it also discuss some assumptions.
For example: SUM(A,N): this algorithm find the sum
of all N elements in vector A. N is integer type
variable indicate there are N elements in Vector A.
39
Algorithm Terminology : format conventions
3. Algorithm steps:
• Actually algorithm is a sequence of numbered steps.
• Each step is begin with a phrase enclosed in square
brackets which gives the sort description about the step.
• The phrase is followed by a set of statements which
describe action to be performed in next line.
For example
2. [ initialize variable I with 0]
I <- 0
40
Algorithm Terminology : format conventions
41
Algorithm Terminology : format conventions
42
Algorithm Terminology : format conventions
• Conditional Statement : IF
we can use if statement in order execute some part
algorithm based on condition.
Syntax is:
IF Condition
Then
Statement 1
Statement 2
-----------
Note: -
We can not use { } to represent the body of if statement.
43
Algorithm Terminology : format conventions
• Conditional Statement : IF -- else
Syntax is:
IF Condition
Then
Statement 1
Statement 2
-----------
Else
Statement 1
Statement 2
-----------
We can also form the else if ladder44
Algorithm Terminology : format conventions
• Repeating statements:-- looping
Three form of looping structure:
1.Repeat for index variable= sequence of values(,)
2.Repeat while <logical expression>
3.Repeat for index= sequence of values while logical exp.
1.
Repeat for I = 1,2,3,4,5,6…….10.
// set of statements
This form is used when a steps are to be repeated for a
counted number of times.45
Algorithm Terminology : format conventions
Repeat for I = 1,2,3,4,5,6…….10.
// set of statements
Here I is loop control variable.
Loop control variable take all values sequentially one by
one.
Once all the set of Statements are in the range are executed
,the loop control variable assume the next value in a
given sequence and again execute the same set of
statements.
No need to write I<- I+1 statement .
46
Algorithm Terminology : format conventions
the loop can be extended over more then one steps in
algorithm.like
1. [ ]
// set of statements
2. [ ]
Repeat thru step 4 for I= 1,2,3,..5
// set of statements
3. [ ]
// set of statements
4. [ ]
// set of statements
5. [ ]
// set of statements
47
Algorithm Terminology : format conventions
2. Repeat while logical expression
// set of statements
Repeat while X<10
write(X)
X <- X+1
Example:
1. [ Phrase]
// set of statements
2. [ Phrase]
Repeat while X<10
write(X)
X <- X+1
3. [ Phrase]48
Algorithm Terminology : format conventions
2. Repeat thru step N while logical expression
// set of statements
Repeat thru step 3 while X<10
write(X)
X <- X+1
Example:
1. [ Phrase]
// set of statements
2. [ Phrase]
Repeat thru step 3 while X<10
write(X)
X <- X+1
3. [ Phrase]49
Algorithm Terminology : format conventions
3. Repeat for index= sequence of values while logical exp.
// set of statements
Or Repeat thru step N for index= sequence of values
while logical exp.
// set of statements
Repeat thru step 3 for I =1,2,3 while X<10
write(X)
50
Algorithm Terminology : format conventions
Go to Statement:
Unconditional transfer of execution control to step
referenced.
Syntax
Goto step N
51
Example : Use of Stack
Example:
String Recognization :
L = { WCWR
| W ∈ { a, b}*} where WR
reverse of String W
Language L define the string of character a and b.
C will act as separator between W and WR
Forexample:
abCba, aabCbaa, abbbCbbba, -- Valid strings
abaCabb --- invalid string
53
String Recognization
Steps:
1. Create stack data structure
2. Read the string from the user
3.Use loop and Push the character onto stack from string
one by one until C (separator) encountered.
4. Once “C” occur in string (do not Push C on the
Stack).stop push operation.
5. Use loop, Pop one element from the stack and fetch one
character from the string after Character C.
6. Check both elements are equals or not . If both are equals
then repeat step 5 and 6 until all character in string are
fetched and top become -1. if at any moments mismatch
occur then stop process. print appropriate message. 54
Algorithm:
• STRRECO: given the string named str of the form WCWR
on
alphabet {a,b,C}.this algorithm determine the whether the
input string str is according to the given language rule or not. S
indicate stack and top is pointer pointing top of the stack.
• 1. [ get the string from the user and initialize the index variable
to get character one by one from the string]
• READ(str)
• I <- 0
• PUSH(S,top,’#’)
• 2.[ fetch one character at a time and push on the stack until
separator C occur in string] .
• repeat while str[i] not ‘C’
• Push(S,top, str[i])
• i <- i +1 55
Algorithm:
3. [scan characters following the ‘C’ one at a time and pop character
from the stack and compare]
i < i +1
repeat while s[i] not NULL
x <- POP (S , top)
if X NOT EQUAL to S[i]
then
Write ( “invalid String”)
goto step 5
4.[ compare the top and end of string simulteneously if step 3 is
successful] .
if S[i]= NULL and S[top] = ‘#’
then
write ( “String is valid”)
else write ( “invalid String”)
56
Algorithm:
5. [finished the algorithm]
exit
57
Stacks

Mais conteúdo relacionado

Mais procurados

Stack data structure
Stack data structureStack data structure
Stack data structure
Tech_MX
 

Mais procurados (20)

Stack and its Applications : Data Structures ADT
Stack and its Applications : Data Structures ADTStack and its Applications : Data Structures ADT
Stack and its Applications : Data Structures ADT
 
Queues
QueuesQueues
Queues
 
Stack and Queue
Stack and Queue Stack and Queue
Stack and Queue
 
Stacks
StacksStacks
Stacks
 
Stacks & Queues By Ms. Niti Arora
Stacks & Queues By Ms. Niti AroraStacks & Queues By Ms. Niti Arora
Stacks & Queues By Ms. Niti Arora
 
Stack and Queue by M.Gomathi Lecturer
Stack and Queue by M.Gomathi LecturerStack and Queue by M.Gomathi Lecturer
Stack and Queue by M.Gomathi Lecturer
 
Stack data structure
Stack data structureStack data structure
Stack data structure
 
Infix to Postfix Conversion Using Stack
Infix to Postfix Conversion Using StackInfix to Postfix Conversion Using Stack
Infix to Postfix Conversion Using Stack
 
Infix to postfix conversion
Infix to postfix conversionInfix to postfix conversion
Infix to postfix conversion
 
Queue in Data Structure
Queue in Data Structure Queue in Data Structure
Queue in Data Structure
 
Applications of stack
Applications of stackApplications of stack
Applications of stack
 
STACK ( LIFO STRUCTURE) - Data Structure
STACK ( LIFO STRUCTURE) - Data StructureSTACK ( LIFO STRUCTURE) - Data Structure
STACK ( LIFO STRUCTURE) - Data Structure
 
Queue data structure
Queue data structureQueue data structure
Queue data structure
 
Data Structures - Lecture 9 [Stack & Queue using Linked List]
 Data Structures - Lecture 9 [Stack & Queue using Linked List] Data Structures - Lecture 9 [Stack & Queue using Linked List]
Data Structures - Lecture 9 [Stack & Queue using Linked List]
 
Data Structure (Queue)
Data Structure (Queue)Data Structure (Queue)
Data Structure (Queue)
 
Stack using Array
Stack using ArrayStack using Array
Stack using Array
 
single linked list
single linked listsingle linked list
single linked list
 
Stacks,queues,linked-list
Stacks,queues,linked-listStacks,queues,linked-list
Stacks,queues,linked-list
 
Linked list
Linked listLinked list
Linked list
 
Stacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURESStacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURES
 

Semelhante a Stacks

Stack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptxStack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptx
chandankumar364348
 
Data structure lecture7
Data structure lecture7Data structure lecture7
Data structure lecture7
Kumar
 

Semelhante a Stacks (20)

DS-UNIT 3 FINAL.pptx
DS-UNIT 3 FINAL.pptxDS-UNIT 3 FINAL.pptx
DS-UNIT 3 FINAL.pptx
 
Stack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptxStack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptx
 
DS UNIT1_STACKS.pptx
DS UNIT1_STACKS.pptxDS UNIT1_STACKS.pptx
DS UNIT1_STACKS.pptx
 
Chapter 4 stack
Chapter 4 stackChapter 4 stack
Chapter 4 stack
 
Chapter 5-stack.pptx
Chapter 5-stack.pptxChapter 5-stack.pptx
Chapter 5-stack.pptx
 
Unit 3 stack
Unit   3 stackUnit   3 stack
Unit 3 stack
 
What is Stack, Its Operations, Queue, Circular Queue, Priority Queue
What is Stack, Its Operations, Queue, Circular Queue, Priority QueueWhat is Stack, Its Operations, Queue, Circular Queue, Priority Queue
What is Stack, Its Operations, Queue, Circular Queue, Priority Queue
 
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manual
 
Data structure lecture7
Data structure lecture7Data structure lecture7
Data structure lecture7
 
Unit II - LINEAR DATA STRUCTURES
Unit II -  LINEAR DATA STRUCTURESUnit II -  LINEAR DATA STRUCTURES
Unit II - LINEAR DATA STRUCTURES
 
Stack and Queue.pptx university exam preparation
Stack and Queue.pptx university exam preparationStack and Queue.pptx university exam preparation
Stack and Queue.pptx university exam preparation
 
Stack in Data Structure
Stack in Data StructureStack in Data Structure
Stack in Data Structure
 
Unit 3 Stacks and Queues.pptx
Unit 3 Stacks and Queues.pptxUnit 3 Stacks and Queues.pptx
Unit 3 Stacks and Queues.pptx
 
Stack Data Structure
Stack Data StructureStack Data Structure
Stack Data Structure
 
5.-Stacks.pptx
5.-Stacks.pptx5.-Stacks.pptx
5.-Stacks.pptx
 
STACK1.pptx
STACK1.pptxSTACK1.pptx
STACK1.pptx
 
Module 2 ppt.pptx
Module 2 ppt.pptxModule 2 ppt.pptx
Module 2 ppt.pptx
 
Stacks in c++
Stacks in c++Stacks in c++
Stacks in c++
 
Chapter 5 Stack and Queue.pdf
Chapter 5 Stack and Queue.pdfChapter 5 Stack and Queue.pdf
Chapter 5 Stack and Queue.pdf
 
Stack in Sata Structure
Stack in Sata StructureStack in Sata Structure
Stack in Sata Structure
 

Mais de sweta dargad

Cyber security tutorial1
Cyber security tutorial1Cyber security tutorial1
Cyber security tutorial1
sweta dargad
 
Open source nms’s
Open source nms’sOpen source nms’s
Open source nms’s
sweta dargad
 

Mais de sweta dargad (11)

Sock Puppet.pptx
Sock Puppet.pptxSock Puppet.pptx
Sock Puppet.pptx
 
RRD Tool and Network Monitoring
RRD Tool and Network MonitoringRRD Tool and Network Monitoring
RRD Tool and Network Monitoring
 
Architecture for SNMP based Network Monitoring System
Architecture for SNMP based Network Monitoring SystemArchitecture for SNMP based Network Monitoring System
Architecture for SNMP based Network Monitoring System
 
Snmp based network monitoring system
Snmp based network monitoring systemSnmp based network monitoring system
Snmp based network monitoring system
 
Applications of RFID technology
Applications of RFID technologyApplications of RFID technology
Applications of RFID technology
 
Cyber security tutorial2
Cyber security tutorial2Cyber security tutorial2
Cyber security tutorial2
 
Cyber security tutorial1
Cyber security tutorial1Cyber security tutorial1
Cyber security tutorial1
 
Classifying Cybercrimes
Classifying CybercrimesClassifying Cybercrimes
Classifying Cybercrimes
 
All about snmp
All about snmpAll about snmp
All about snmp
 
Open source nms’s
Open source nms’sOpen source nms’s
Open source nms’s
 
Cacti
CactiCacti
Cacti
 

Último

UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
rknatarajan
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Christo Ananth
 

Último (20)

Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdf
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...
 
Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
NFPA 5000 2024 standard .
NFPA 5000 2024 standard                                  .NFPA 5000 2024 standard                                  .
NFPA 5000 2024 standard .
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
UNIT-IFLUID PROPERTIES & FLOW CHARACTERISTICS
UNIT-IFLUID PROPERTIES & FLOW CHARACTERISTICSUNIT-IFLUID PROPERTIES & FLOW CHARACTERISTICS
UNIT-IFLUID PROPERTIES & FLOW CHARACTERISTICS
 

Stacks

  • 1. Stacks CS 308 – Data Structures
  • 2. What is a stack? • It is an ordered group of homogeneous items of elements. • Elements are added to and removed from the top of the stack (the most recently added items are at the top of the stack). • The last element to be added is the first to be removed (LIFO: Last In, First Out).
  • 3. Stack • Stack operations may involve initializing the stack, using it and then de-initializing it. Apart from these basic stuffs, a stack is used for the following two primary operations − •  push() − Pushing (storing) an element on the stack. •  pop() − Removing (accessing) an element from the stack. • When data is PUSHed onto stack. • To use a stack efficiently, we need to check the status of stack as well. For the same
  • 4. •  peek() − get the top data element of the stack, without removing it. •  isFull() − check if stack is full. •  isEmpty() − check if stack is empty. • At all times, we maintain a pointer to the last PUSHed data on the stack. As this pointer • always represents the top of the stack, hence named top. The top pointer provides top • value of the stack without actually removing it.
  • 5. peek() • Implementation of peek() function in C programming language − • int peek() { • return stack[top]; • }
  • 6. isfull() • bool isfull() { • if(top == MAXSIZE) • return true; • else • return false; • }
  • 7. isempty() • Implementation of isempty() function in C programming language is slightly different. We initialize top at -1, as the index in array starts from 0. So we check if the top is below zero or -1 to determine if the stack is empty. Here's the code − • bool isempty() { • if(top == -1) • return true; • else • return false; • }
  • 8. 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, produces an error 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.
  • 9. Impelementation in C • void push(int data) { • if(!isFull()) { • top = top + 1; • stack[top] = data; • }else { • printf("Could not insert data, Stack is full.n"); • } • }
  • 10.
  • 11. Pop Operation • Accessing the content while removing it from the stack, is known as a Pop Operation. In an array implementation of pop() operation, the data element is not actually removed, instead top is decremented to a lower position in the stack to point to the next value. But in linked-list implementation, pop() actually removes data element and deallocates memory space.
  • 12. • Step 1 − Checks if the stack is empty. • Step 2 − If the stack is empty, produces an error and exit. • Step 3 − If the stack is not empty, accesses the data element at which top is • pointing. • Step 4 − Decreases the value of top by 1. • Step 5 − Returns success. Impelementation in C
  • 13.
  • 14. int pop(int data) { if(!isempty()) { data = stack[top]; top = top - 1; return data; }else { printf("Could not retrieve data, Stack is empty.n"); } }
  • 15.
  • 16. Stack Implementation #include <stdio.h> int MAXSIZE = 8; int stack[8]; int top = -1; int isempty() { if(top == -1) return 1; else return 0; } int isfull() { if(top == MAXSIZE) return 1; else return 0; }
  • 17. Stack Implementation (cont.) • int peek() { • return stack[top]; • } • int pop() { • int data; • if(!isempty()) { • data = stack[top]; • top = top - 1; • return data; • }else { • printf("Could not retrieve data, Stack is empty.n"); • }
  • 18. Stack Implementation (cont.) int push(int data) { if(!isfull()) { top = top + 1; stack[top] = data; }else { printf("Could not insert data, Stack is full.n"); } } int main() { // push items on to the stack push(3); push(5); push(9); push(1); push(12); push(15); printf("Element at top of the stack: %dn" ,peek()); printf("Elements: n");
  • 19. //print stack data while(!isempty()) { int data = pop(); printf("%dn",data); } printf("Stack full: %sn" , isfull()?"true":"false"); printf("Stack empty: %sn" , isempty()?"true":"false"); return 0; }
  • 20. Output • Element at top of the stack: 15 • Elements: • 15 • 12 • 1 • 9 • 5 • 3 • Stack full: false • Stack empty: true
  • 21. 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);
  • 22. Expression Parsing • The way to write arithmetic expression is known as a notation. An arithmetic expression • can be written in three different but equivalent notations, i.e., without changing the • essence or output of an expression. These notations are − •  Infix Notation •  Prefix (Polish) Notation •  Postfix (Reverse-Polish) Notation
  • 23. Example: postfix expressions • Postfix notation is another way of writing arithmetic expressions. • In postfix notation, the operator is written after the two operands. infix: 2+5 postfix: 2 5 + • Expressions are evaluated from left to right. • Precedence rules and parentheses are never needed!!
  • 26. Postfix expressions: Algorithm using stacks WHILE more input items exist Get an item IF item is an operand stack.Push(item) ELSE stack.Pop(operand2) stack.Pop(operand1) Compute result stack.Push(result) stack.Pop(result)
  • 27. Write the body for a function that replaces each copy of an item in a stack with another item. Use the following specification. (this function is a client program). ReplaceItem(StackType& stack, ItemType oldItem, ItemType newItem) Function: Replaces all occurrences of oldItem with newItem. Precondition: stack has been initialized. Postconditions: Each occurrence of oldItem in stack has been replaced by newItem. (You may use any of the member functions of the StackType, but you may not assume any knowledge of how the stack is implemented).
  • 28. { ItemType item; StackType tempStack; while (!Stack.IsEmpty()) { Stack.Pop(item); if (item==oldItem) tempStack.Push(newItem); else tempStack.Push(item); } while (!tempStack.IsEmpty()) { tempStack.Pop(item); Stack.Push(item); } } 1 2 3 3 5 1 1 5 3 Stack Stack tempStack oldItem = 2 newItem = 5
  • 29. Exercises • 1, 3-7, 14, 12, 15, 18, 19
  • 30. Infix to Postfix • Infix notation is easier for humans to read and understand whereas for electronic machines • like computers, postfix is the best form of expression to parse. We shall see here a program • to convert and evaluate infix notation to postfix notation −
  • 31. Program • #include<stdio.h> • #include<string.h> • //char stack • char stack[25]; • int top = -1; • void push(char item) { • stack[++top] = item; • } • char pop() { • return stack[top--]; • }
  • 32. • //returns precedence of operators • int precedence(char symbol) { • switch(symbol) { • case '+': • case '-': • return 2; • break; • case '*': • case '/': • return 3; • break;
  • 33. • case '^': • return 4; • break; • case '(': • case ')': • case '#': • return 1; • break; • } • }
  • 34. //check whether the symbol is operator? • int isOperator(char symbol) { • switch(symbol) { • case '+': • case '-': • case '*': • case '/': • case '^': • case '(': • case ')': • return 1; • break; • default: • return 0; }
  • 35. //converts infix expression to postfix • void convert(char infix[],char postfix[]) { • int i,symbol,j = 0; • stack[++top] = '#'; • for(i = 0;i<strlen(infix);i++) { • symbol = infix[i]; • if(isOperator(symbol) == 0) { • postfix[j] = symbol; • j++;
  • 36. • } else { • if(symbol == '(') { • push(symbol); • }else { • if(symbol == ')') { • while(stack[top] != '(') { • postfix[j] = pop(); • j++; • }
  • 37. • pop();//pop out (. • } else { • if(precedence(symbol)>precedence(stack[top])) { • push(symbol); • }else { • while(precedence(symbol)<=precedence(stack[top ])) { • postfix[j] = pop(); • j++;
  • 38. Algorithm • An algorithm is a sequence of finite number of steps to solve a specific problem. • A algorithm can be defined as well –defined step by step computational procedure which takes set of values as input and produce set of values as output. • A finite set of instruction that followed to accomplish a particular task. 38
  • 39. Algorithm Terminology : format conventions 1. Name of algorithm: every algorithm is given an identifying name. the name written in capital letter. 2. Introductory comments: the algorithms name is followed by a brief introduction regarding the task the algorithm will perform. in addition it also discuss some assumptions. For example: SUM(A,N): this algorithm find the sum of all N elements in vector A. N is integer type variable indicate there are N elements in Vector A. 39
  • 40. Algorithm Terminology : format conventions 3. Algorithm steps: • Actually algorithm is a sequence of numbered steps. • Each step is begin with a phrase enclosed in square brackets which gives the sort description about the step. • The phrase is followed by a set of statements which describe action to be performed in next line. For example 2. [ initialize variable I with 0] I <- 0 40
  • 41. Algorithm Terminology : format conventions 41
  • 42. Algorithm Terminology : format conventions 42
  • 43. Algorithm Terminology : format conventions • Conditional Statement : IF we can use if statement in order execute some part algorithm based on condition. Syntax is: IF Condition Then Statement 1 Statement 2 ----------- Note: - We can not use { } to represent the body of if statement. 43
  • 44. Algorithm Terminology : format conventions • Conditional Statement : IF -- else Syntax is: IF Condition Then Statement 1 Statement 2 ----------- Else Statement 1 Statement 2 ----------- We can also form the else if ladder44
  • 45. Algorithm Terminology : format conventions • Repeating statements:-- looping Three form of looping structure: 1.Repeat for index variable= sequence of values(,) 2.Repeat while <logical expression> 3.Repeat for index= sequence of values while logical exp. 1. Repeat for I = 1,2,3,4,5,6…….10. // set of statements This form is used when a steps are to be repeated for a counted number of times.45
  • 46. Algorithm Terminology : format conventions Repeat for I = 1,2,3,4,5,6…….10. // set of statements Here I is loop control variable. Loop control variable take all values sequentially one by one. Once all the set of Statements are in the range are executed ,the loop control variable assume the next value in a given sequence and again execute the same set of statements. No need to write I<- I+1 statement . 46
  • 47. Algorithm Terminology : format conventions the loop can be extended over more then one steps in algorithm.like 1. [ ] // set of statements 2. [ ] Repeat thru step 4 for I= 1,2,3,..5 // set of statements 3. [ ] // set of statements 4. [ ] // set of statements 5. [ ] // set of statements 47
  • 48. Algorithm Terminology : format conventions 2. Repeat while logical expression // set of statements Repeat while X<10 write(X) X <- X+1 Example: 1. [ Phrase] // set of statements 2. [ Phrase] Repeat while X<10 write(X) X <- X+1 3. [ Phrase]48
  • 49. Algorithm Terminology : format conventions 2. Repeat thru step N while logical expression // set of statements Repeat thru step 3 while X<10 write(X) X <- X+1 Example: 1. [ Phrase] // set of statements 2. [ Phrase] Repeat thru step 3 while X<10 write(X) X <- X+1 3. [ Phrase]49
  • 50. Algorithm Terminology : format conventions 3. Repeat for index= sequence of values while logical exp. // set of statements Or Repeat thru step N for index= sequence of values while logical exp. // set of statements Repeat thru step 3 for I =1,2,3 while X<10 write(X) 50
  • 51. Algorithm Terminology : format conventions Go to Statement: Unconditional transfer of execution control to step referenced. Syntax Goto step N 51
  • 52.
  • 53. Example : Use of Stack Example: String Recognization : L = { WCWR | W ∈ { a, b}*} where WR reverse of String W Language L define the string of character a and b. C will act as separator between W and WR Forexample: abCba, aabCbaa, abbbCbbba, -- Valid strings abaCabb --- invalid string 53
  • 54. String Recognization Steps: 1. Create stack data structure 2. Read the string from the user 3.Use loop and Push the character onto stack from string one by one until C (separator) encountered. 4. Once “C” occur in string (do not Push C on the Stack).stop push operation. 5. Use loop, Pop one element from the stack and fetch one character from the string after Character C. 6. Check both elements are equals or not . If both are equals then repeat step 5 and 6 until all character in string are fetched and top become -1. if at any moments mismatch occur then stop process. print appropriate message. 54
  • 55. Algorithm: • STRRECO: given the string named str of the form WCWR on alphabet {a,b,C}.this algorithm determine the whether the input string str is according to the given language rule or not. S indicate stack and top is pointer pointing top of the stack. • 1. [ get the string from the user and initialize the index variable to get character one by one from the string] • READ(str) • I <- 0 • PUSH(S,top,’#’) • 2.[ fetch one character at a time and push on the stack until separator C occur in string] . • repeat while str[i] not ‘C’ • Push(S,top, str[i]) • i <- i +1 55
  • 56. Algorithm: 3. [scan characters following the ‘C’ one at a time and pop character from the stack and compare] i < i +1 repeat while s[i] not NULL x <- POP (S , top) if X NOT EQUAL to S[i] then Write ( “invalid String”) goto step 5 4.[ compare the top and end of string simulteneously if step 3 is successful] . if S[i]= NULL and S[top] = ‘#’ then write ( “String is valid”) else write ( “invalid String”) 56
  • 57. Algorithm: 5. [finished the algorithm] exit 57