Stacks This presentation shows – how to implement the stack – how it can be used in real applications.

Slides:



Advertisements
Similar presentations
Stacks, Queues, and Linked Lists
Advertisements

Chapter 3: Lists, Stacks and Queues Concept of Abstract Data Type (ADTS) How to efficiently perform operations on list Stack ADT and its applications Queue.
CS201: Data Structures and Discrete Mathematics I Linked Lists, Stacks and Queues.
LIST PROCESSING.
Data Structure Lecture-3 Prepared by: Shipra Shukla Assistant Professor Kaziranga University.
Stack & Queues COP 3502.
Senem Kumova Metin Spring2009 STACKS AND QUEUES Chapter 10 in A Book on C.
Chapter 6 Structures By C. Shing ITEC Dept Radford University.
Templates in C++ Template function in C++ makes it easier to reuse classes and functions. A template can be viewed as a variable that can be instantiated.
Data Structures Lecture 13: QUEUES Azhar Maqsood NUST Institute of Information Technology (NIIT)
CSCE 3110 Data Structures & Algorithm Analysis Stacks and Queues Reading: Chap.3 Weiss.
More on Stacks and Queues. As we mentioned before, two common introductory Abstract Data Type (ADT) that worth studying are Stack and Queue Many problems.
CS Data Structures II Review COSC 2006 April 14, 2017
CS113 Introduction to C Instructor: Ioannis A. Vetsikas Lecture 7 : September 8.
Lecture 5 Sept 15 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Stacks CS-240 Dick Steflik. Stacks Last In, First Out operation - LIFO As items are added they are chronologically ordered, items are removed in reverse.
Lecture 7 Sept 16 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Stacks CS-240 Dick Steflik. Stacks Last In, First Out operation - LIFO As items are added they are chronologically ordered, items are removed in reverse.
Stacks CS-240 Dick Steflik. Stacks Last In, First Out operation - LIFO As items are added they are chronologically ordered, items are removed in reverse.
Lecture 6 Feb 12 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Stacks, Queues & Deques CSC212.
CHAPTER 6 Stacks Array Implementation. 2 Stacks A stack is a linear collection whose elements are added and removed from one end The last element to be.
CHAPTER 6 Stacks. 2 A stack is a linear collection whose elements are added and removed from one end The last element to be put on the stack is the first.
Stacks CS-240 & CS-341 Dick Steflik. Stacks Last In, First Out operation - LIFO As items are added they are chronologically ordered, items are removed.
Stack  A stack is a linear data structure or abstract data type for collection of items, with the restriction that items can be added one at a time and.
Chapter 7 Stacks II CS Data Structures I COSC 2006
Ceng-112 Data Structures ITurgut Kalfaoglu 1 Chapter 3 Stacks.
Implementing Stacks Ellen Walker CPSC 201 Data Structures Hiram College.
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
Review 1 Introduction Representation of Linear Array In Memory Operations on linear Arrays Traverse Insert Delete Example.
Data Structures. The Stack: Definition A stack is an ordered collection of items into which new items may be inserted and from which items may be deleted.
DATA STRUCTURES AND ALGORITHMS Lecture Notes 4 Prepared by İnanç TAHRALI.
COP3530 Data Structures600 Stack Stack is one the most useful ADTs. Like list, it is a collection of data items. Supports “LIFO” (Last In First Out) discipline.
IKI 10100: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100: Lecture6.
Min Chen School of Computer Science and Engineering Seoul National University Data Structure: Chapter 3.
EASTERN MEDITERRANEAN UNIVERSITY Stacks EENG212 –Algorithms and Data Structures.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
1 Linked-list, stack and queue. 2 Outline Abstract Data Type (ADT)‏ Linked list Stack Queue.
APS105 Lists. Structures Arrays allow a collection of elements –All of the same type How to collect elements of different types? –Structures; in C: struct.
1 Stacks & Queues CSC Stacks & Queues Stack: Last In First Out (LIFO). –Used in procedure calls, to compute arithmetic expressions etc. Queue: First.
Stacks An Abstract Data Type. Restricted Access Unlike arrays, stacks only allow the top most item to be accessed at any time The interface of a stack.
Data Structures. Abstract Data Type A collection of related data is known as an abstract data type (ADT) Data Structure = ADT + Collection of functions.
Definition: A stack is an ordered collection of elements in which insertions(Push) and deletions(Pop) are restricted to one end. LIFO(Last In First Out)
2005MEE Software Engineering Lecture 7 –Stacks, Queues.
Fall 2006 METU EEEEE 441 S. Ece (GURAN) SCH MIDT EE 441 Data Structures Lecture 6 Stacks and Queues.
Data Structures David Kauchak cs302 Spring Data Structures What is a data structure? Way of storing data that facilitates particular operations.
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
Linked Lists Data Structures and Algorithms CS 244 Brent M. Dingle, Ph.D. Department of Mathematics, Statistics, and Computer Science University of Wisconsin.
Click to edit Master text styles Stacks Data Structure.
1 Data Structures and Algorithms Stack. 2 The Stack ADT Introduction to the Stack data structure Designing a Stack class using dynamic arrays Linked Stacks.
CE 221 Data Structures and Algorithms Chapter 3: Lists, Stacks, and Queues - II Text: Read Weiss, §3.6 1Izmir University of Economics.
Lecture No.05 Data Structures Dr. Sohail Aslam.  Josephus Problem #include "CList.cpp" void main(int argc, char *argv[]) { CList list; int i, N=10, M=3;
1 Data Structures and Algorithms Stack. 2 The Stack ADT Introduction to the Stack data structure Designing a Stack class using dynamic arrays Linked Stacks.
 In general, Queue is line of person waiting for their turn at some service counter like ticket window at cinema hall, at bus stand or at railway station.
CSCE 3110 Data Structures & Algorithm Analysis
Review Array Array Elements Accessing array elements
Data Structures and Algorithms
Queues Queues Queues.
Stacks.
Stack and Queue APURBO DATTA.
Stack.
Stack and Queue.
Pointers and Linked Lists
CSCE 3110 Data Structures & Algorithm Analysis
Data Structures and Algorithms
COMPUTER 2430 Object Oriented Programming and Data Structures I
Cs212: Data Structures Computer Science Department Lecture 6: Stacks.
Stacks Data structure Elements added, removed from one end only
Stacks CS-240 Dick Steflik.
Abstract Data Types Stacks CSCI 240
Presentation transcript:

Stacks This presentation shows – how to implement the stack – how it can be used in real applications

Stack Definitions Stack: a linear data structure where access is restricted to the most recently inserted item. Stack operations: -Push: add an item to the stack. -Pop: remove an item from the stack. The element to be removed is the last item added. -Isempty: Check if the stack is empty Derived operations: -Top: read the element on the top (can be implemented using one pop followed by read and push the element again) -DeleteStack: Pop all elements of the stack (can be elemented by successive calls to pop)

Stack Interface A typical stack interface (function declaration): void push(Thing newThing); Thing pop(); Thing top(); char isempty(); Thing: could be char, int, float, double, or structure isempty() returns 1 if stack is empty, zero otherwise

6 th Mar 2007 Stack Implementation: Array A stack can be implemented as an array A and an integer top that records the index of the top of the stack. For an empty stack, set top to -1. When push(X) is called, increment top, and write X to A[top]. When pop() is called, decrement top. When top() is called, return A[top].

Example A top A B Push A Push B top 0 1 A B 0 Pop

Stack Implementation: Linked List A stack can be implemented as a linked list A with a pointer head that points to the top of the stack. For an empty stack, set head to NULL. When push(X) is called, add node to the front (see previous lecture) When pop() is called, remove node from the front (see previous lecture)

Stack Implementation: Array #include # define maxstacksize 1000; Typedef struct elem{ // Stack item represented as a strcture int dataitem1; char dataitem2; }elem; elem stackarray[maxstacksize]; int top=-1; void push(elem newelem); elem pop(); elem top(); char isempty(); // returns 1 if true, zero otherwise Void push(elem newelem){ if(top==maxstacksize-1){ printf (“stack is full \n”); return(); } top++; stackarray[top]=newelem; } Type Definitions & ConstantsCreating empty stackStack Function declarationFunction implementation

Stack Implementation: Array elem pop(){ if(top==-1){ printf (“stack is empty \n”); } else{ top--; return (stackarray[top+1]); } elem top(){ if(top==-1){ printf (“stack is empty \n”); return(); } return (stackarray[top]); } char isempty(){ if (top==-1){return (1);} else{return (0);} } Function implementation

Stack Implementation: Linked List #include Typedef struct elem{ // Stack item represented as a strcture int dataitem1; char dataitem2; struct elem* next; }elem; elem* headptr; void push(elem newelem); elem pop(); elem top(); char isempty(); // returns 1 if true, zero otherwise Void push(elem newelem){ elem* new = (node*) malloc( sizeof( struct t_node ) ); if(new==NULL) {printf(“not enough memory\n”); return (0);} *new = *newelem; new->next=NULL; new->next = *headptr; *headptr = new; return(1); } Type Definitions & ConstantsCreating empty stackStack Function declarationFunction implementation

Stack Implementation: Linked List elem pop(){ elem tmp; elem* tmp_ptr=headptr; if(isempty()){ printf (“stack is empty \n”); return(); } tmp=*headptr; headptr = headptr->next; free(tmp_ptr); return (tmp); } elem top(){ if(isempty()){ printf (“stack is empty \n”); return(); } return (*headptr); } char isempty(){ if (headptr==NULL){return (1);} else{return (0);} } Function implementation

Stack in Action: Infix Calculator Problem: Build an infix calculator –Input: A mathematical expression of integer numbers represented by a string. –Ouput: A numerical value evaluating the expresion -Constraint: each closed bracket should be in the form “(term operation term)”, where term could be a number or another bracket, and operation is either (‘+’, ‘-’, ‘*’, ‘/’). -Example: ((3*4)-5)+2) accepted input -Example: ((3*4)-5+2) not accepted input  Here, we will assume that the user carefully enters the data. But it is recommended you think of a function that checks if the user input is correct or not  Think what the word “infix” mean; what is related could exist?  Here, we will assume that the user carefully enters the data. But it is recommended you think of a function that checks if the user input is correct or not  Think what the word “infix” mean; what is related could exist?

Stack in Action: Infix Calculator The idea of the algorithm is Push elements as long as elements are not “)” Once you meet “)”, start pop elements until you find “(”and evaluate sub expression store it in variable total, pop also the first “(” you see. Push the value total back to the stack Example: ((3*4)-5)+2) is evaluated as follows ( ((3*4)-5)+2) Push element

Stack in Action: Infix Calculator The idea of the algorithm is Push elements as long as elements are not “)” Once you meet “)”, start pop elements until you find “(”and evaluate sub expression store it in variable total, pop also the first “(” you see. Push the value total back to the stack Example: ((3*4)-5)+2) is evaluated as follows ( ( ((3*4)-5)+2) Push element

Stack in Action: Infix Calculator The idea of the algorithm is Push elements as long as elements are not “)” Once you meet “)”, start pop elements until you find “(”and evaluate sub expression store it in variable total, pop also the first “(” you see. Push the value total back to the stack Example: ((3*4)-5)+2) is evaluated as follows 3 ( ( ((3*4)-5)+2) Push element

Stack in Action: Infix Calculator The idea of the algorithm is Push elements as long as elements are not “)” Once you meet “)”, start pop elements until you find “(”and evaluate sub expression store it in variable total, pop also the first “(” you see. Push the value total back to the stack Example: ((3*4)-5)+2) is evaluated as follows * 3 ( ( ((3*4)-5)+2) Push element

Stack in Action: Infix Calculator The idea of the algorithm is Push elements as long as elements are not “)” Once you meet “)”, start pop elements until you find “(”and evaluate sub expression store it in variable total, pop also the first “(” you see. Push the value total back to the stack Example: ((3*4)-5)+2) is evaluated as follows 4 * 3 ( ( ((3*4)-5)+2) Push element

Stack in Action: Infix Calculator The idea of the algorithm is Push elements as long as elements are not “)” Once you meet “)”, start pop elements until you find “(”and evaluate sub expression store it in variable total, pop also the first “(” you see. Push the value total back to the stack Example: ((3*4)-5)+2) is evaluated as follows 4 * 3 ( ( ((3*4)-5)+2) Do not push element, pop ‘4’, ‘*’, ‘3’, ‘)’ and evaluate them, then return total back

Stack in Action: Infix Calculator The idea of the algorithm is Push elements as long as elements are not “)” Once you meet “)”, start pop elements until you find “(”and evaluate sub expression store it in variable total, pop also the first “(” you see. Push the value total back to the stack Example: ((3*4)-5)+2) is evaluated as follows 12 ( ((3*4)-5)+2) Do not push element, pop ‘4’, ‘*’, ‘3’, ‘)’ and evaluate them, then return total back

Stack in Action: Infix Calculator The idea of the algorithm is Push elements as long as elements are not “)” Once you meet “)”, start pop elements until you find “(”and evaluate sub expression store it in variable total, pop also the first “(” you see. Push the value total back to the stack Example: ((3*4)-5)+2) is evaluated as follows - 12 ( ((3*4)-5)+2) Push element

Stack in Action: Infix Calculator The idea of the algorithm is Push elements as long as elements are not “)” Once you meet “)”, start pop elements until you find “(”and evaluate sub expression store it in variable total, pop also the first “(” you see. Push the value total back to the stack Example: ((3*4)-5)+2) is evaluated as follows ( ((3*4)-5)+2) Push element

Stack in Action: Infix Calculator The idea of the algorithm is Push elements as long as elements are not “)” Once you meet “)”, start pop elements until you find “(”and evaluate sub expression store it in variable total, pop also the first “(” you see. Push the value total back to the stack Example: ((3*4)-5)+2) is evaluated as follows ( ((3*4)-5)+2) Do not push element, pop ‘5’, ‘-’, ‘12’, ‘)’ and evaluate them, then return total back

Stack in Action: Infix Calculator The idea of the algorithm is Push elements as long as elements are not “)” Once you meet “)”, start pop elements until you find “(”and evaluate sub expression store it in variable total, pop also the first “(” you see. Push the value total back to the stack Example: ((3*4)-5)+2) is evaluated as follows 7 ( ((3*4)-5)+2) Do not push element, pop ‘5’, ‘-’, ‘12’, ‘)’ and evaluate them, then return total back

Stack in Action: Infix Calculator The idea of the algorithm is Push elements as long as elements are not “)” Once you meet “)”, start pop elements until you find “(”and evaluate sub expression store it in variable total, pop also the first “(” you see. Push the value total back to the stack Example: ((3*4)-5)+2) is evaluated as follows ( ((3*4)-5)+2) Push elements ‘+’ & ‘2’

Stack in Action: Infix Calculator The idea of the algorithm is Push elements as long as elements are not “)” Once you meet “)”, start pop elements until you find “(”and evaluate sub expression store it in variable total, pop also the first “(” you see. Push the value total back to the stack Example: ((3*4)-5)+2) is evaluated as follows ( ((3*4)-5)+2) Do not push element, pop ‘2’, ‘+’, ‘7’, ‘)’ and evaluate them, then return total back

Stack in Action: Infix Calculator The idea of the algorithm is Push elements as long as elements are not “)” Once you meet “)”, start pop elements until you find “(”and evaluate sub expression store it in variable total, pop also the first “(” you see. Push the value total back to the stack Example: ((3*4)-5)+2) is evaluated as follows 9 ((3*4)-5)+2) Do not push element, pop ‘2’, ‘+’, ‘7’, ‘)’ and evaluate them, then return total back

Stack in Action: Infix Calculator The idea of the algorithm is Push elements as long as elements are not “)” Once you meet “)”, start pop elements until you find “(”and evaluate sub expression store it in variable total, pop also the first “(” you see. Push the value total back to the stack Example: ((3*4)-5)+2) is evaluated as follows ((3*4)-5)+2) Return 9

Main Interface for Calc. Program //// stack declaration and implementation is given above int parse_expres(char* inputstr, elem* expres_tokens); float evaluate_expres(elem* expres_tokens, int expres_length); int main(int argc, char *argv[]) { char inchar; char inputstr[1000]; float retval; elem expres_tokens[1000]; int expres_length=0; while(1){ printf(“Enter 0 to exit, or 1 to enter an expression\n”); scanf(“%c”,&inchar); if(char==‘0’){ exit(0);} else if(char==‘1’){ printf(“Enter an expression\n”); scanf(“%s”,inputstr); expres_length=parse_expres(inputstr, expres_tokens); retval=evaluate_expres(expres_tokens, expres_length); print(“Expression evaluates to %f \n”, retval); } //else } // while return(0); } // main Function call Function declaration

Parsing the Expression int parse_expres(char* inputstr, elem* expres_tokens){ char numdigits[100]; numdigits[j]=0; // end of string int i=0; int j=0; int k=0; int val; int strlength=0; strlength=strlen(inputstr); for (i=0;i<strlength;i++){ if(isdigit(inputstr[i])){ numdigits[j]=inputstr[i]; j++; numdigits[j]=0; // end of string } else{ j=0; if(strlen(numdigit)>0){ // indicates I just read a number val=atoi(numdigits); numdigits[0]=0; // make the string empty express_token[k].dataitem1=0; express_token[k].dataitem2=val; } if(inputstr[i]==‘+’) expres_token[k].dataitem1=1; if(inputstr[i]==‘-’) expres_token[k].dataitem1=2; if(inputstr[i]==‘*’) expres_token[k].dataitem1=3; if(inputstr[i]==‘/’) expres_token[k].dataitem1=4; if(inputstr[i]==‘(’) expres_token[k].dataitem1=5; if(inputstr[i]==‘)’) expres_token[k].dataitem1=6; k++; } //else }// for loop } // function

Parsing the Expression int parse_expres(char* inputstr, elem* expres_tokens){ char numdigits[100]; numdigits[j]=0; // end of string int i=0; int j=0; int k=0; int val; int strlength=0; strlength=strlen(inputstr); for (i=0;i<strlength;i++){ if(isdigit(inputstr[i])){ numdigits[j]=inputstr[i]; j++; numdigits[j]=0; // end of string } else{ j=0; if(strlen(numdigit)>0){ // indicates I just read a number val=atoi(numdigits); numdigits[0]=0; // make the string empty express_token[k].dataitem1=0; express_token[k].dataitem2=val; } if(inputstr[i]==‘+’) expres_token[k].dataitem1=1; if(inputstr[i]==‘-’) expres_token[k].dataitem1=2; if(inputstr[i]==‘*’) expres_token[k].dataitem1=3; if(inputstr[i]==‘/’) expres_token[k].dataitem1=4; if(inputstr[i]==‘(’) expres_token[k].dataitem1=5; if(inputstr[i]==‘)’) expres_token[k].dataitem1=6; k++; } //else }// for loop } // function The function isdigit checks if the input character is in the set {0,1,2,3,…,9}

Evaluate the Expression float evaluate_expres(elem* expres_tokens, int expres_length){ int i=0; elem tmpelem; int value1, int value2, int optype, float total; for(i=0;i<expres_length;i=++){ if(expres_tokens[i].dataitem1!=6){ push(expres_tokens[i]); } else{ if(isempty()==0){tmpelem=pop();} else{printf(“Wrong expres”); exit(1);} value1=tmpelem.dataitem2; // pops value if(isempty()==0){tmpelem=pop();} else{printf(“Wrong expres”); exit(1);} optype=tmpelem.dataitem1; //pops operation if(isempty()==0){tmpelem=pop();} else{printf(“Wrong expres”); exit(1);} value2=tmpelem.dataitem2; // the following pops out “(” if(isempty()==0){tmpelem=pop();} else{printf(“Wrong expres”); exit(1);} if(optype==1){total=value1+value2;} if(optype==2){total=value2-value1;} if(optype==3){total=value1*value2;} if(optype==4){total=(float)value2/(float)value1;} tmpelem.dataitem1=0; tmpelem.dataitem2=total; push(tmpelem); } else } // endfor if(isempty()==0){tmpelem=pop();} else{printf(“Wrong expres”); exit(1);} if(isempty()){return(tmpelem.dataitem2);}else{printf(“Wrong expres”); exit(1);} } // function

Evaluate the Expression float evaluate_expres(elem* expres_tokens, int expres_length){ int i=0; elem tmpelem; int value1, int value2, int optype, float total; for(i=0;i<expres_length;i=++){ if(expres_tokens[i].dataitem1!=6){ push(expres_tokens[i]); } else{ if(isempty()==0){tmpelem=pop();} else{printf(“Wrong expres”); exit(1);} value1=tmpelem.dataitem2; // pops value if(isempty()==0){tmpelem=pop();} else{printf(“Wrong expres”); exit(1);} optype=tmpelem.dataitem1; //pops operation if(isempty()==0){tmpelem=pop();} else{printf(“Wrong expres”); exit(1);} value2=tmpelem.dataitem2; // the following pops out “(” if(isempty()==0){tmpelem=pop();} else{printf(“Wrong expres”); exit(1);} if(optype==1){total=value1+value2;} if(optype==2){total=value2-value1;} if(optype==3){total=value1*value2;} if(optype==4){total=(float)value2/(float)value1;} tmpelem.dataitem1=0; tmpelem.dataitem2=total; push(tmpelem); } else } // endfor if(isempty()==0){tmpelem=pop();} else{printf(“Wrong expres”); exit(1);} if(isempty()){return(tmpelem.dataitem2);}else{printf(“Wrong expres”); exit(1);} } // function If stack is empty before finishing evaluation, then expression must be syntactically wrong If stack remains non-empty after finishing expression, then expression must be syntactically wrong Without the constraint on the expression, we could have more than pops. If stack is empty before finishing evaluation, then expression must be syntactically wrong If stack remains non-empty after finishing expression, then expression must be syntactically wrong Without the constraint on the expression, we could have more than pops.

T HE E ND