CE 221 Data Structures and Algorithms

Slides:



Advertisements
Similar presentations
Data Structures Through C
Advertisements

Stacks, Queues, and Linked Lists
§3 The Stack ADT 1. ADT A stack is a Last-In-First-Out (LIFO) list, that is, an ordered list in which insertions and deletions are.
CS Data Structures ( 資料結構 ) Chapter 3: Stacks and Queues Spring 2012.
Stacks - 3 Nour El-Kadri CSI Evaluating arithmetic expressions Stack-based algorithms are used for syntactical analysis (parsing). For example.
C o n f i d e n t i a l Developed By Nitendra NextHome Subject Name: Data Structure Using C Title : Overview of Stack.
 Balancing Symbols 3. Applications
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Data Structures Stacks.
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.
Objectives of these slides:
Ceng-112 Data Structures ITurgut Kalfaoglu 1 Chapter 3 Stacks.
1 Stacks – Chapter 3 A stack is a data structure in which all insertions and deletions of entries are made at one end, called the top of the stack. Alternatively,
Week7 Stack Data Structures & Algorithms. Introduction to Stacks and Queues Widely used data structures Ordered List of element Easy to implement Easy.
CSC 205 Programming II Postfix Expressions. Recap: Stack Stack features Orderly linear structure Access from one side only – top item Stack operations.
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
Chapter 4 Stacks Stacks A stack is a linear data structure that can be accessed only at one of its ends for storing and retrieving. Its called.
Computer Science Department Data Structure & Algorithms Problem Solving with Stack.
Stacks 1. Stack  What is a stack? An ordered list where insertions and deletions occur at one end called the top. Also known as last-in-first-out (LIFO)
CHAPTER 3 Lists, Stacks, and Queues §1 Abstract Data Type (ADT) 【 Definition 】 Data Type = { Objects }  { Operations } 〖 Example 〗 int = { 0,  1, 
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.
CHAPTER 3 STACK CSEB324 DATA STRUCTURES & ALGORITHM.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 19: Stacks and Queues (part 2)
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 18: Stacks and Queues (part 2)
CE 221 Data Structures and Algorithms Chapter 4: Trees (Binary) Text: Read Weiss, §4.1 – 4.2 1Izmir University of Economics.
CE 221 Data Structures and Algorithms Chapter 6: Priority Queues (Binary Heaps) Text: Read Weiss, §6.1 – 6.3 1Izmir University of Economics.
CE 221 Data Structures and Algorithms
CE 221 Data Structures and Algorithms Chapter 3: Lists, Stacks, and Queues - II Text: Read Weiss, §3.6 1Izmir University of Economics.
Copyright © Curt Hill Stacks An Useful Abstract Data Type.
CHP-3 STACKS.
Stacks A stack is a linear data structure that can be accessed only at one of its ends for storing and retrieving data LIFO (Last In First Out) 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.
CC 215 DATA STRUCTURES MORE ABOUT STACK APPLICATIONS Dr. Manal Helal - Fall 2014 Lecture 6 AASTMT Engineering and Technology College 1.
Applications of Stack Maitrayee Mukerji. Stacks Last In First Out (LIFO List) ◦ FILO? Insertions and Deletions from the same end called the Top Push(),
CE 221 Data Structures and Algorithms Chapter 3: Lists, Stacks, and Queues - II Text: Read Weiss, §3.6 1Izmir University of Economics.
 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.
Chapter 3 Lists, Stacks, Queues. Abstract Data Types A set of items – Just items, not data types, nothing related to programming code A set of operations.
Chapter 4 Stacks
CS 201 Data Structures and Algorithms
Stacks Stacks.
Revised based on textbook author’s notes.
CE 221 Data Structures and Algorithms
CS 201 Data Structures and Algorithms
MEMORY REPRESENTATION OF STACKS
Stacks.
Stacks Stack: restricted variant of list
Stacks Chapter 4.
Data Structures – Week #3
Algorithms and Data Structures
Stack.
Stacks Chapter 5 Adapted from Pearson Education, Inc.
Mark Allen Weiss, Addison Wesley
CE 221 Data Structures and Algorithms
Stacks and Queues 1.
Cs212: Data Structures Computer Science Department Lecture 6: Stacks.
CE 221 Data Structures and Algorithms
CE 221 Data Structures and Algorithms
Stacks and Queues Prof. Michael Tsai 2017/02/21.
Stacks.
Topic 15 Implementing and Using Stacks
CE 221 Data Structures and Algorithms
Jordi Cortadella and Jordi Petit Department of Computer Science
(Part 2) Infix, Prefix & Postfix
Stacks Chapter 5.
Stacks and Queues CSE 373 Data Structures.
Stack.
17CS1102 DATA STRUCTURES © 2016 KL University – The contents of this presentation are an intellectual and copyrighted property of KL University. ALL RIGHTS.
Chapter 7 (continued) © 2011 Pearson Addison-Wesley. All rights reserved.
Presented by : Aman Gupta PGT CS KV No.1, Narimedu, Madurai
Presentation transcript:

CE 221 Data Structures and Algorithms Chapter 3: Lists, Stacks, and Queues - II Text: Read Weiss, §3.6 Izmir University of Economics

The Stack ADT – Stack Model A stack (LIFO list) is a list with the restriction that inserts and deletes can be performed in only one position, namely the end of the list called the top. The two operations on a stack are push, pop (also top to examine the item at the top). While pop on an empty stack is generally considered an ADT error, running out of space when performing a push is an implementation error but not an ADT error. Izmir University of Economics

Implementation of Stacks Since a stack is a list, any list implementation will do. Singly Linked List implementation of a stack: push by inserting at the front, pop by deleting the element at the front. Array implementation of stack: It is the more popular solution. It uses the InsertToBack and DeleteFromBack from the Vector implementation. Associated with each stack is Array and TopOfStack which is set to -1 for an empty stack. #define Error(Str) FatalError(Str) #define FatalError(Str) fprintf(stderr, "%s\n", Str), exit(1) #define EmptyTOS ( -1 ) #define MinStackSize ( 5 ) typedef int ElementType; struct StackRecord { int Capacity; int TopOfStack; ElementType *Array; }; typedef struct StackRecord *Stack; Izmir University of Economics

Array Implementation of Stacks - I int IsEmpty( Stack S ){ return S->TopOfStack == EmptyTOS; } int IsFull( Stack S ){ return S->TopOfStack == S->Capacity - 1; Stack CreateStack( int MaxElements ){ Stack S; if(MaxElements<MinStackSize) Error("Stack size is too small"); S = malloc( sizeof( struct StackRecord ) ); if(S == NULL) FatalError("Out of space!!!"); S->Array = malloc(sizeof(ElementType)*MaxElements); if(S->Array == NULL) FatalError("Out of space!!!"); S->Capacity = MaxElements; MakeEmpty(S); return S; Izmir University of Economics

Array Implementation of Stacks - II void Push(ElementType X, Stack S){ if( IsFull( S ) ) Error( "Full stack" ); else S->Array[ ++S->TopOfStack ] = X; } void Pop( Stack S ){ if( IsEmpty( S ) ) Error( "Empty stack" ); S->TopOfStack--; void MakeEmpty(Stack S){ S->TopOfStack = EmptyTOS; } void DisposeStack(Stack S){ if( S != NULL ){ free( S->Array ); free( S ); ElementType Top( Stack S ){ /* TopandPop is similar */ if( !IsEmpty( S ) ) return S->Array[ S->TopOfStack ]; Error( "Empty stack" ); return 0; /* Return value used to avoid warning */ } Izmir University of Economics

Stack Applications - Balancing Symbols Compilers check programs for syntax errors, but frequently a lack of one symbol (such as a missing brace or comment starter) will cause the compiler to spill out a hundred lines of diagnostics. Thus, every right brace, bracket, and parenthesis must correspond to their left counterparts. Example: The sequence [()] is legal, but [(]) is not. stack  Ø; while (!eof(file)){ read(char); if (isOpening(char)) push(char, stack); else if (isClosing(char)) if (isEmpty(stack) error(); else cchar = topAndPop(stack); if (!isMatching(char,cchar)) } if (!isEmpty(stack)) It is clearly linear and actually makes only one pass through the input. It is thus on-line and quite fast. Izmir University of Economics

Stack Applications – Postfix Expressions Order of evaluation for arithmetic expressions depending on the precedence and associativity of operators has a huge impact on the result of the evaluation. Example: 4.99 + 5.99 + 6.99 * 1.06 = produces either 19.05, or 18.39. Most simple four-function calculators will give the first answer, but better calculators know that multiplication has higher precedence than addition. A scientific calculator generally comes with parentheses, so we can always get the right answer by parenthesizing, but with a simple calculator we need to remember intermediate results. Izmir University of Economics

Izmir University of Economics Postfix Notation (((a*b)+c)+(d*e)) fully parenthesized T1=a*b, T1=T1+c, T2=d*e, T1=T1+T2 by using intermediate results a b * c + d e * + is the equivalent of using intermediate results. This notation is known as postfix or reverse Polish notation. Notice that when an expression is given in postfix notation, there is no need to know any precedence rules. Izmir University of Economics

Postfix Expression Evaluation 6 5 2 3 + 8 * + 3 + * First four symbols are placed on the stack. This algorithm depicted below is clearly O(N) + 8 * + 3 + * 8 * + 3 + * * + 3 + * + 3 + * 3 + * + * * Izmir University of Economics

Infix to Postfix Conversion We can use stacks to convert an expression in standart (also known as infix) form into postfix. Example: operators = {+, *, (, )}, We apply usual precedence rules; Infix: a + b * c + (d * e + f) * g Postfix: a b c * + d e * f + g * + Izmir University of Economics

Infix to Postfix - Algorithm stack  Ø; while (! eos(expr)){ read(char); if (isOperand(char)) output(char); else if (char == “)”) while ((!isEmpty(stack))&&((sc=topAndPop(stack))!= “(”)) output(sc); else while ( (!isEmpty(stack)) && inStackPriority(top(stack))>=(outStackPriority(char)))) output(topAndPop(stack)); push(char, stack); } while (!isEmpty(stack)) output(pop(stack)); inStackPriority outStackPriority ** (RL) 4 5 *, / (LR) 3 +, - (LR) 2 ( 1 6 inStackPriority(“(”)=very low outStackPriority(“(”)=very high Izmir University of Economics

Example I Example: Infix equation is (A+B/C*(D+E)-F). What is postfix version of it? Symbol Stack Postfix Priority: ^ , (*, / , %), (+,-) ------------------------------------------------------------------------------------------------------------------------- ( ( A ( A + ( + A B ( + A B / ( + / A B C ( + / A B C * ( + / * A B C / Pop the operator with higher or eq. Priority, so pop / ( ( + * ( A B C / D ( + * ( A B C / D + ( + * ( + A B C / D E ( + * ( + A B C / D E ) ( + * ( + ) A B C / D E + Bracket closes pop + and remove parantheses - ( + * - A B C / D E + * Higher priority must come before lower, so pop * ( + - A B C / D E + * + Equal priority cannot stay together, so pop + F ( - A B C / D E + * + F ) ( - ) A B C / D E + * + F - Bracket closes pop - and remove ( and )

Infix to Postfix Using stack – Example 2 1: a + b * c + (d * e + f) * g 4: (d * e + f) * g 2: * c + (d * e + f) * g 5: * e + f) * g 3: + (d * e + f) * g Izmir University of Economics

Infix to Postfix Using stack – Example 2 6: + f) * g 8: * g 7: ) * g Izmir University of Economics

Izmir University of Economics Function Calls The algorithm to check balanced symbols suggests a way to implement function calls. The problem here is that when a call is made to a new function, all the variables local to the calling routine need to be saved by the system. Furthermore, the current location in the routine must be saved so that the new function knows where to go after it is done. “(“ and “)” are exactly like function call and function return. Every PL implementing recursion has that mechanism. The information saved is called either an activation record or stack frame. There is always the possibility that you will run out of stack space by having too many simultaneously active functions. On many systems there is no checking for overflow. Izmir University of Economics

Function Calls and Recursion The routine print_list printing out a linked list, is perfectly legal and actually correct. It properly handles the base case of an empty list, and the recursion is fine. Unfortunately, if the list contains 20,000 elements, there will be a stack of 20,000 activation records (and hence possibly a program crash). An example of an extremely bad use of recursion known as tail recursion (recursive call at the last line). It can be automatically eliminated by enclosing the body in a while loop and replacing the recursive call with one assignment per function argument. void print_list( LIST L ){ while (1) { if( L != NULL ){ print_element(L->element); L = L->next; } void print_list( LIST L ) { if( L != NULL ) { print_element(L->element); print_list( L->next ); } Izmir University of Economics

Izmir University of Economics Homework Assignments 3.23, 3.24, 3.25.a, You are requested to study and solve the exercises. Note that these are for you to practice only. You are not to deliver the results to me. Izmir University of Economics