Data Structures and Programming 資料結構與程式設計. Topic 6 Stacks. Stacks. Stack of Cups. Stacks. top. top. bottom. bottom

Size: px
Start display at page:

Download "Data Structures and Programming 資料結構與程式設計. Topic 6 Stacks. Stacks. Stack of Cups. Stacks. top. top. bottom. bottom"

Transcription

1 Data Structures and Programming 資料結構與程式設計 Topic 6 Stacks 課程編號 : EE 30 科目名稱 : 資料結構與程式設計授課教師 : 黃鼎偉時間地點 : 一 678 電機二館 229 Stacks Linear list. One end is called top. Other end is called bottom. Additions to and removals from the top end only. 2 Stack of Cups top bottom E D C B A top bottom Add a cup to the stack. Remove a cup from new stack. A stack is a LIFO (last-in first-out) list. F E D C B A Stacks template<class T> 2 class stack 3 { 4 public: 5 virtual ~stack() {} 6 virtual bool empty() const = 0; 7 virtual int size() const = 0; 8 virtual T& top() = 0; 9 virtual void pop() = 0; 0 virtual void push(const T& theelement) = 0; }; 3 stack.h 4

2 Derive From A Linear List Class arraylist chain Derive From arraylist stack top is either left end or right end of linear list empty() => arraylist::empty() O() time size() => arraylist::size() O() time top() => get(0) or get(size() ) O() time 5 6 Derive From arraylist Derive From arraylist when top is left end of linear list push(theelement) => insert(0, theelement) O(size) time pop() => erase(0) O(size) time when top is right end of linear list push(theelement) => insert(size(), theelement) O() time pop() => erase(size() ) O() time use right end of list as top of stack 7 8

3 Derive From chain firstnode Derive From chain firstnode NULL stack top is either left end or right end of linear list empty() => chain::empty() O() time size() => chain::size() O() time NULL when top is left end of linear list top() => get(0) O() time push(theelement) => insert(0, theelement) O() time pop() => erase(0) O() time 9 0 Derive From chain firstnode null when top is right end of linear list top() => get(size() ) O(size) time push(theelement) => insert(size(), theelement) O(size) time pop() => erase(size() ) O(size) time use left end of list as top of stack Derive From arraylist and its Constructor template<class T> 2 class derivedarraystack : 3 private arraylist<t>, 4 public stack<t> 5 { 6 public: 7 // code for stack methods comes here 8 9 }; 0 derivedarraystack(int initialcapacity = 0) : arraylist<t> (initialcapacity) {} derivedarraystack.h 2

4 empty() and size() bool empty() const 2 { 3 return arraylist<t>::empty(); 4 } 5 6 int size() const 7 { 8 return arraylist<t>::size(); 9 } top() T& top() 2 { 3 if (arraylist<t>::empty()) 4 throw stackempty(); 5 return get(arraylist<t>::size() ); 6 } derivedarraystack.h 3 derivedarraystack.h 4 push(theelement) void push(const T& theelement) 2 { 3 insert(arraylist<t>::size(), theelement); 4 } pop() void pop() 2 { 3 if (arraylist<t>::empty()) 4 throw stackempty(); 5 erase(arraylist<t>::size() ); 6 } derivedarraystack.h 5 derivedarraystack.h 6

5 Evaluation Merits of deriving from arraylist Code for derived class is quite simple and easy to develop. Code is expected to require little debugging. Code for other stack implementations such as a linked implementation are easily obtained. Just replace private arraylist<t> with private chain<t> For efficiency reasons we must also make changes to use the left end of the list as the stack top rather than the right end. Demerits Unnecessary work is done by the code. top() verifies that the stack is not empty before get is invoked. The index check done by get is, therefore, not needed. insert(size(), theelement) does an index check and a copy_backward. Neither is needed. pop() verifies that the stack is not empty before erase is invoked. erase does an index check and a copy. Neither is needed. So the derived code runs slower than necessary. 7 8 Evaluation Code developed from scratch will run faster but will take more time (cost) to develop. Tradeoff between software development cost and performance. Tradeoff between time to market and performance. Could develop easy code first and later refine it to improve performance. A Faster pop() if (arraylist<t>::empty()) 2 throw stackempty(); 3 erase(arraylist<t>::size() ); try 2 { erase(arraylist<t>::size() );} 3 catch (illegalindex) 4 {throw stackempty();} 9 derivedarraystack.h vs derivedarraystackwithcatch.h 20

6 Code From Scratch arraystack Use a D array stack whose data type is T. same as using array element in arraylist Use an int variable stacktop. Stack elements are in stack[0:stacktop]. Top element is in stack[stacktop]. Bottom element is in stack[0]. Stack is empty iff stacktop =. Number of elements in stack is stacktop +. Class arraystack template class<t> 2 class arraystack : public stack<t> 3 { 4 public: 5 // public methods come here 6 private: 7 int stacktop; // current top of stack 8 int arraylength; // stack capacity 9 T *stack; // element array 0 }; 2 arraystack.h 22 Constructor 2 template<class T> 3 arraystack<t>::arraystack(int initialcapacity) 4 { 5 // Constructor. 6 if (initialcapacity < ) 7 { 8 // code to throw an exception comes here 9 } 0 arraylength = initialcapacity; stack = new T[arrayLength]; 2 stacktop = ; 3 } push( ) template<class T> 2 void arraystack<t>::push(const T& theelement) 3 { 4 // Add theelement to stack. 5 if (stacktop == arraylength ) 6 { 7 // code to double capacity coms here 8 } 9 // add at stack top 0 stack[++stacktop] = theelement; } top arraystack.h 23 arraystack.h 24

7 pop() void pop() 2 { 3 if (stacktop == ) 4 throw stackempty(); 5 stack[stacktop ].~T(); // destructor for T 6 } top Code From Scratch linkedstack 4 template<class T> 5 class linkedstack : public stack<t> 6 { 7 public: 8 linkedstack(int initialcapacity = 0) 9 {stacktop = NULL; stacksize = 0;} 20 ~linkedstack(); 2 bool empty() const 22 {return stacksize == 0;} 23 int size() const 24 {return stacksize;} 25 T& top() 26 { 27 if (stacksize == 0) 28 throw stackempty(); 29 return stacktop >element; 30 } 3 void pop(); 32 void push(const T& theelement) 33 { 34 stacktop = new chainnode<t>(theelement, stacktop); 35 stacksize++; 36 } 37 private: 38 chainnode<t>* stacktop; // pointer to stack top 39 int stacksize; // number of elements in stack 40 }; arraystack.h 25 linkedstack.h 26 Performance 50,000,000 pop, push, and peek operations initial capacity Class default 50,000,000 arraystack 2.7s.5s STL stack 5.6s - derivedarraystack 7.5s 6.3s linkedstack 40.5s 40.5s derivedlinkedstack 4.0s 4.0s Applications Parentheses Matching Towers of Hanoi/Brahma Rearranging Railroad Cars Routing A 2-pin Net Method Invocation And Return Try-Throw-Catch Chess Story Eight Queens Puzzle Knight s Tour Eight Puzzle 27 28

8 Parentheses Matching (((a+b)*c+d-e)/(f+g)-(h+j)*(k-l))/(m-n) Output pairs (u,v) such that the left parenthesis at position u is matched with the right parenthesis at v. (2,6) (,3) (5,9) (2,25) (27,3) (0,32) (34,38) (a+b))*((c+d) (0,4) right parenthesis at 5 has no matching left parenthesis (8,2) left parenthesis at 7 has no matching right parenthesis Parentheses Matching scan expression from left to right when a left parenthesis is encountered, add its position to the stack when a right parenthesis is encountered, remove matching position from stack parenthesismatching.cpp 29 parenthesismatching.cpp 30 Example Towers of Hanoi/Brahma (((a+b)*c+d-e)/(f+g)-(h+j)*(k-l))/(m-n) 34 (2,6) (,3) (5,9) (2,25) (27,3) (0,32) and so on 64 gold disks to be moved from tower A to tower C each tower operates as a stack cannot place big disk on top of a smaller one parenthesismatching.cpp

9 Towers of Hanoi/Brahma Towers of Hanoi/Brahma disk Towers of Hanoi/Brahma 2 3-disk Towers of Hanoi/Brahma 3 hanoiusingstacks.cpp 33 hanoiusingstacks.cpp 34 Towers of Hanoi/Brahma Towers of Hanoi/Brahma disk Towers of Hanoi/Brahma disk Towers of Hanoi/Brahma hanoiusingstacks.cpp 35 hanoiusingstacks.cpp 36

10 Towers of Hanoi/Brahma Towers of Hanoi/Brahma 3-disk Towers of Hanoi/Brahma disk Towers of Hanoi/Brahma 2 hanoiusingstacks.cpp 37 hanoiusingstacks.cpp 38 Towers of Hanoi/Brahma Towers of Hanoi/Brahma 3 3-disk Towers of Hanoi/Brahma 2 3-disk Towers of Hanoi/Brahma disk moveshanoiusingstacks.cpp hanoiusingstacks.cpp 39 40

11 Recursive Solution Recursive Solution n > 0 gold disks to be moved from A to C using B move top disk from A to C move top n disks from A to B using C 4 hanoirecursive.cpp 42 Recursive Solution Recursive Solution move top n disks from B to C using A moves(n) = 0 when n = 0 moves(n) = 2*moves(n ) + = 2 n when n > 0 hanoirecursive.cpp 43 44

12 Towers of Hanoi/Brahma Rearranging Railroad Cars moves(64) =.8 * 0 9 (approximately) Performing 0 9 moves/second, a computer would take about 570 years to complete. At disk move/min, the monks will take about 3.4 * 0 3 years. [ ] Input track H H H3 9 Output track [ ] Input track Output track H H2 H3 hanoirecursive.cpp 45 railroadwithstacks.cpp 46 Switch Box Routing Routing region Routing A 2-pin Net Routing for pins -3 and 8-40 is confined to lower left region Routing for pins 5 through6 is confined to upper right region switchbox.cpp 47 switchbox.cpp 48

13 Routing A 2-pin Net Routing A 2-pin Net (u,v), u<v is a 2-pin net. u is start pin. v is end pin Examine pins in clock-wise order beginning with pin Start pin => push onto stack. End pin => start pin must be at top of stack switchbox.cpp 49 switchbox.cpp 50 Move order is: right, down, left, up Block positions to avoid revisit. maze.cpp 5 52

14 Move order is: right, down, left, up Move backward until we reach a square from which a forward move is possible. Block positions to avoid revisit Move down. Move left. maze.cpp 55 maze.cpp 56

15 Move down. Move backward until we reach a square from which a forward move is possible. maze.cpp 57 maze.cpp 58 Move backward until we reach a square from which a forward move is possible. Move right. Backtrack. Move downward. maze.cpp 59 maze.cpp 60

16 Move downward. Move right. maze.cpp 6 maze.cpp 62 Move one down and then right. Move one up and then right. maze.cpp 63 maze.cpp 64

17 Method Invocation And Return Move down to exit and eat cheese. Path from maze entry to current position operates public void a() { ; b(); } public void b() { ; c(); } public void c() { ; d(); } public void d() { ; e(); } return address in d() return address in c() return address in e() return address in d() return address in c() return address in b() public void e() { ; c(); } return address in a() as a stack. maze.cpp Try-Throw-Catch When you enter a try block, push the address of this block on a stack. When an exception is thrown, pop the try block that is at the top of the stack (if the stack is empty, terminate). If the popped try block has no matching catch block, go back to the preceding step. If the popped try block has a matching catch block, execute the matching catch block. 67 Chess Story grain of rice on the first square, 2 for next, 4 for next, 8 for next, and so on. Surface area needed exceeds surface area of earth. 68

18 Chess Story penny for the first square, 2 for next, 4 for next, 8 for next, and so on. $3.6 * 0 7 (federal budget ~ $2 * 0 2 ). Eight Queens Puzzle The eight queens puzzle is the problem of placing eight chess queens on an 8 8 chessboard so that none of them can capture any other using the standard chess queen's moves. The queens must be placed in such a way that no two queens attack each other. Using stack to store the recursive steps of moves Knight s Tour The knight's tour is a mathematical problem involving a knight on a chessboard. The knight is placed on the empty board and, moving according to the rules of chess, must visit each square exactly once. A knight's tour is called a closed tour if the knight ends on a square attacking the square from which it began (so that it may tour the board again immediately with the same path). Otherwise the tour is open. Eight Puzzle Using Stack to store the best moves. Using stack to store the recursive steps of moves 7 72

Data Structures and Programming 資料結構與程式設計. Topic 3 Linear Lists Array. AbstractDataType linearlist. Linear List - Array Representation

Data Structures and Programming 資料結構與程式設計. Topic 3 Linear Lists Array. AbstractDataType linearlist. Linear List - Array Representation Data Structures and Programming 資料結構與程式設計 Topic 3 Linear Lists Array 課程編號 :901 31900 EE 3011 科目名稱 : 資料結構與程式設計授課教師 : 黃鼎偉時間地點 : 一 678 電機二館 229 Abstract Data Type linearlist Abstract Data Type (ADT) AbstractDataType

More information

Derive From A Linear List Class. Stacks. Derive From ArrayLinearList. Derive From ArrayLinearList. Derive From ArrayLinearList.

Derive From A Linear List Class. Stacks. Derive From ArrayLinearList. Derive From ArrayLinearList. Derive From ArrayLinearList. Stacks Derive From A Linear List Class public interface Stack public boolean empty(); public Object peek(); public void push(object theobject); public Object pop(); ArrayLinearList Chain ƒ stack top is

More information

Abstract Data Type array. 1D Array Representation In C++ Space Overhead. Data Structures and Programming 資料結構與程式設計. Topic 5 Arrays and Matrices

Abstract Data Type array. 1D Array Representation In C++ Space Overhead. Data Structures and Programming 資料結構與程式設計. Topic 5 Arrays and Matrices Data Structures and Programming 資料結構與程式設計 Topic 5 Arrays and Matrices 課程編號 :901 31900 EE 3011 科目名稱 : 資料結構與程式設計授課教師 : 黃鼎偉時間地點 : 一 678 電機二館 229 Abstract Data Type array Abstract Data Type (ADT) AbstractDataType

More information

Stacks and Their Applications

Stacks and Their Applications Chapter 5 Stacks and Their Applications We have been discussing general list structures. In practice, we often work with some restricted cases, in which insertions and/or deletions occur only at one or

More information

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100 Department of Electronics and Communication

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100 Department of Electronics and Communication INTERNAL ASSESSMENT TEST 1 Date : 28.2.2018 Marks: 40 Subject & Code : DataStructures Using C++ (15EC661) Sem : VI A,B,C Name of faculty : Vandana M L Time : 11:30-1:00 PM Note: Answer FIVE full questions,

More information

STACKS AND QUEUES. Problem Solving with Computers-II

STACKS AND QUEUES. Problem Solving with Computers-II STACKS AND QUEUES Problem Solving with Computers-II 2 Stacks container class available in the C++ STL Container class that uses the Last In First Out (LIFO) principle Methods i. push() ii. iii. iv. pop()

More information

Foundations of Data Structures

Foundations of Data Structures Foundations of Data Structures Lecture 4 Elementary Abstract Data Types (ADT): Stack Queue 1 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies:

More information

class Polynomial { public: Polynomial(const string& N = "no name", const vector<int>& C = vector<int>());... };

class Polynomial { public: Polynomial(const string& N = no name, const vector<int>& C = vector<int>());... }; Default Arguments 1 When declaring a C++ function, you may optionally specify a default value for function parameters by listing initializations for them in the declaration: class Polynomial { public:

More information

IV. Stacks. A. Introduction 1. Consider the 4 problems on pp (1) Model the discard pile in a card game. (2) Model a railroad switching yard

IV. Stacks. A. Introduction 1. Consider the 4 problems on pp (1) Model the discard pile in a card game. (2) Model a railroad switching yard IV. Stacks 1 A. Introduction 1. Consider the problems on pp. 170-1 (1) Model the discard pile in a card game (2) Model a railroad switching yard (3) Parentheses checker () Calculate and display base-two

More information

Data Structures. data object. set or collection of instances. integer = {0, +1, -1, +2, -2, +3, -3, } daysofweek = {S,M,T,W,Th,F,Sa}

Data Structures. data object. set or collection of instances. integer = {0, +1, -1, +2, -2, +3, -3, } daysofweek = {S,M,T,W,Th,F,Sa} Data Structures data object set or collection of instances integer = {0, +1, -1, +2, -2, +3, -3, } daysofweek = {S,M,T,W,Th,F,Sa} Data Object instances may or may not be related mydataobject = {apple,

More information

CMPSCI 187: Programming With Data Structures. Lecture 12: Implementing Stacks With Linked Lists 5 October 2011

CMPSCI 187: Programming With Data Structures. Lecture 12: Implementing Stacks With Linked Lists 5 October 2011 CMPSCI 187: Programming With Data Structures Lecture 12: Implementing Stacks With Linked Lists 5 October 2011 Implementing Stacks With Linked Lists Overview: The LinkedStack Class from L&C The Fields and

More information

Stacks Fall 2018 Margaret Reid-Miller

Stacks Fall 2018 Margaret Reid-Miller Stacks 15-121 Fall 2018 Margaret Reid-Miller Today Exam 2 is next Tuesday, October 30 Today: Quiz 5 solutions Recursive add from last week (see SinglyLinkedListR.java) Stacks ADT (Queues on Thursday) ArrayStack

More information

Stacks. Chapter 5. Copyright 2012 by Pearson Education, Inc. All rights reserved

Stacks. Chapter 5. Copyright 2012 by Pearson Education, Inc. All rights reserved Stacks Chapter 5 Copyright 2012 by Pearson Education, Inc. All rights reserved Contents Specifications of the ADT Stack Using a Stack to Process Algebraic Expressions A Problem Solved: Checking for Balanced

More information

Performance Analysis. Space Complexity. Instruction Space. Data Structures and Programming 資料結構與程式設計. Topic 2 Complexity Analysis.

Performance Analysis. Space Complexity. Instruction Space. Data Structures and Programming 資料結構與程式設計. Topic 2 Complexity Analysis. Performace Aalysis Data Structures ad Programmig 資料結構與程式設計 Topic 2 Complexity Aalysis 課程編號 :901 31900 EE 3011 科目名稱 : 資料結構與程式設計授課教師 : 黃鼎偉時間地點 : 一 678 電機二館 229 Performace of a Program Performace aalysis

More information

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100 Department of Electronics and Communication

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100 Department of Electronics and Communication USN 1 P E PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -0 Department of Electronics and Communication INTERNAL ASSESSMENT TEST 1 Date : 30/8/2017 Marks: 0 Subject & Code

More information

Data Structures (INE2011)

Data Structures (INE2011) Data Structures (INE2011) Electronics and Communication Engineering Hanyang University Haewoon Nam Lecture 4 1 Stacks Insertion and deletion are made at one end () Last input first output (LIFO) Inserting

More information

The Stack ADT. Stacks. The Stack ADT. The Stack ADT. Set of objects in which the location an item is inserted and deleted is prespecified.

The Stack ADT. Stacks. The Stack ADT. The Stack ADT. Set of objects in which the location an item is inserted and deleted is prespecified. The Stack ADT Stacks Set of objects in which the location an item is inserted and deleted is prespecified Stacks! Insert in order! Delete most recent item inserted! LIFO - last in, first out Stacks 2 The

More information

CMPSCI 187: Programming With Data Structures. Lecture #11: Implementing Stacks With Arrays David Mix Barrington 28 September 2012

CMPSCI 187: Programming With Data Structures. Lecture #11: Implementing Stacks With Arrays David Mix Barrington 28 September 2012 CMPSCI 187: Programming With Data Structures Lecture #11: Implementing Stacks With Arrays David Mix Barrington 28 September 2012 Implementing Stacks With Arrays The Idea of the Implementation Data Fields

More information

Containers: Stack. The Stack ADT. The Stack ADT. The Stack ADT

Containers: Stack. The Stack ADT. The Stack ADT. The Stack ADT Containers: Stack The Stack ADT A stack is a list of objects in which insertions and deletions can only be performed at the top of the list. Also known as LIFO Last In, First Out) push insert an element

More information

Containers: Stack. Jordi Cortadella and Jordi Petit Department of Computer Science

Containers: Stack. Jordi Cortadella and Jordi Petit Department of Computer Science Containers: Stack Jordi Cortadella and Jordi Petit Department of Computer Science The Stack ADT A stack is a list of objects in which insertions and deletions can only be performed at the top of the list.

More information

Link-Based Implementations. Chapter 4

Link-Based Implementations. Chapter 4 Link-Based Implementations Chapter 4 Overview Assignment-2 Slack code puzzle Negative time durations Both -1:59:59 and -0:00:01 are OK to represent -1 seconds Slack no assignment code posting Code Puzzle

More information

CSC 222: Computer Programming II. Spring 2004

CSC 222: Computer Programming II. Spring 2004 CSC 222: Computer Programming II Spring 2004 Stacks and recursion stack ADT push, pop, top, empty, size vector-based implementation, library application: parenthesis/delimiter matching run-time

More information

More Group HW. #ifndef Stackh #define Stackh. #include <cstdlib> using namespace std;

More Group HW. #ifndef Stackh #define Stackh. #include <cstdlib> using namespace std; More Group HW The following code is contained in the file ex1stck.h. Fill in the blanks with the C++ statement(s) that will correctly finish the method. Each blank may be filled in with more than one statement.

More information

Introduction. Problem Solving on Computer. Data Structures (collection of data and relationships) Algorithms

Introduction. Problem Solving on Computer. Data Structures (collection of data and relationships) Algorithms Introduction Problem Solving on Computer Data Structures (collection of data and relationships) Algorithms 1 Objective of Data Structures Two Goals: 1) Identify and develop useful high-level data types

More information

Data Structures And Algorithms

Data Structures And Algorithms Data Structures And Algorithms Stacks Eng. Anis Nazer First Semester 2017-2018 Stack An Abstract data type (ADT) Accessed only on one end Similar to a stack of dishes you can add/remove on top of stack

More information

CS350: Data Structures Stacks

CS350: Data Structures Stacks Stacks James Moscola Department of Engineering & Computer Science York College of Pennsylvania James Moscola Stacks Stacks are a very common data structure that can be used for a variety of data storage

More information

Stacks. stacks of dishes or trays in a cafeteria. Last In First Out discipline (LIFO)

Stacks. stacks of dishes or trays in a cafeteria. Last In First Out discipline (LIFO) Outline stacks stack ADT method signatures array stack implementation linked stack implementation stack applications infix, prefix, and postfix expressions 1 Stacks stacks of dishes or trays in a cafeteria

More information

Stacks and their Applications

Stacks and their Applications Stacks and their Applications Lecture 23 Sections 18.1-18.2 Robb T. Koether Hampden-Sydney College Fri, Mar 16, 2018 Robb T. Koether Hampden-Sydney College) Stacks and their Applications Fri, Mar 16, 2018

More information

Stack and Queue. Stack:

Stack and Queue. Stack: Stack and Queue Stack: Abstract Data Type A stack is a container of objects that are inserted and removed according to the last-in first-out (LIFO) principle. In the pushdown stacks only two operations

More information

September 19,

September 19, September 19, 2013 1 Problems with previous examples Changes to the implementation will require recompilation & relinking of clients Extensions will require access to the source code Solutions Combine

More information

Stacks. Ordered list with property: Insertions and deletions always occur at the same end. INSERT DELETE A3 A3 TOP TOP TOP

Stacks. Ordered list with property: Insertions and deletions always occur at the same end. INSERT DELETE A3 A3 TOP TOP TOP Stacks Ordered list with property: Insertions and deletions always occur at the same end. INSERT A3 A3 TOP DELETE A2 TOP A2 A2 TOP A1 A1 A1 A0 A0 A0 Stacks Implementation Implementation with arrays: Declare

More information

Stacks. Gaddis 18.1, Molly A. O'Neil CS 2308 :: Spring 2016

Stacks. Gaddis 18.1, Molly A. O'Neil CS 2308 :: Spring 2016 Stacks Gaddis 18.1, 18.3 Molly A. O'Neil CS 2308 :: Spring 2016 The Stack ADT A stack is an abstract data type that stores a collection of elements of the same type The elements of a stack are accessed

More information

CMPT 225. Lecture 9 Stack

CMPT 225. Lecture 9 Stack CMPT 225 Lecture 9 Stack 1 Last Lecture We did an activity about Stack 2 Learning Outcomes 3 At the end of this lecture (and the activity), a student will be able to: Describe Stack Define public interface

More information

Stacks (5.1) Abstract Data Types (ADTs) CSE 2011 Winter 2011

Stacks (5.1) Abstract Data Types (ADTs) CSE 2011 Winter 2011 Stacks (5.1) CSE 2011 Winter 2011 26 January 2011 1 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: Data stored Operations on the data Error

More information

CS 171: Introduction to Computer Science II. Stacks. Li Xiong

CS 171: Introduction to Computer Science II. Stacks. Li Xiong CS 171: Introduction to Computer Science II Stacks Li Xiong Today Stacks operations and implementations Applications using stacks Application 1: Reverse a list of integers Application 2: Delimiter matching

More information

1. Algorithm. Data Structures & Algorithms. How many times you weight? Algo 2 : Half Cutting. How many times you weight? Algo.1 :Two coins at a time

1. Algorithm. Data Structures & Algorithms. How many times you weight? Algo 2 : Half Cutting. How many times you weight? Algo.1 :Two coins at a time Data Structures & Algorithms Lecturer : Kritawan Siriboon,, Room no. 93 Text : Data Structures & Algorithm Analysis in C, C, Mark Allen Weiss, Addison Wesley. Algorithm State how to solve problem step

More information

CS200: Recursion and induction (recap from cs161)

CS200: Recursion and induction (recap from cs161) CS200: Recursion and induction (recap from cs161) Prichard Ch. 6.1 & 6.3 1 2 Backtracking n Problem solving technique that involves moves: guesses at a solution. n Depth First Search: in case of failure

More information

CS302 Data Structures using C++

CS302 Data Structures using C++ CS302 Data Structures using C++ Midterm Exam Instructor: Dr. Kostas Alexis Teaching Assistants: Shehryar Khattak, Mustafa Solmaz Semester: Fall 2018 Date: November 7 2018 Student First Name Student Last

More information

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR STUDENT IDENTIFICATION NO MULTIMEDIA COLLEGE JALAN GURNEY KIRI 54100 KUALA LUMPUR FIFTH SEMESTER FINAL EXAMINATION, 2014/2015 SESSION PSD2023 ALGORITHM & DATA STRUCTURE DSEW-E-F-2/13 25 MAY 2015 9.00 AM

More information

COMP6771 Advanced C++ Programming

COMP6771 Advanced C++ Programming 1. COMP6771 Advanced C++ Programming Week 4 Part One: (continued) and 2016 www.cse.unsw.edu.au/ cs6771 2. Inline Constructors, Accessors and Mutators Question (from 2015): In the week 3 examples, constructors

More information

University of Illinois at Urbana-Champaign Department of Computer Science. Second Examination

University of Illinois at Urbana-Champaign Department of Computer Science. Second Examination University of Illinois at Urbana-Champaign Department of Computer Science Second Examination CS 225 Data Structures and Software Principles Fall 2011 9a-11a, Wednesday, November 2 Name: NetID: Lab Section

More information

CHAPTER 3 STACKS AND QUEUES. Iris Hui-Ru Jiang Fall 2008

CHAPTER 3 STACKS AND QUEUES. Iris Hui-Ru Jiang Fall 2008 HAPTER 3 STAKS AND QUEUES Iris Hui-Ru Jiang Fall 2008 2 ontents Templates in ++ Stack (LIFO) Queue (FIFO) Subtyping and Inheritance in ++ A Mazing Problem Evaluation of Expressions Readings hapter 3 ++

More information

COMP250: Stacks. Jérôme Waldispühl School of Computer Science McGill University. Based on slides from (Goodrich & Tamassia, 2004)

COMP250: Stacks. Jérôme Waldispühl School of Computer Science McGill University. Based on slides from (Goodrich & Tamassia, 2004) COMP250: Stacks Jérôme Waldispühl School of Computer Science McGill University Based on slides from (Goodrich & Tamassia, 2004) 2004 Goodrich, Tamassia The Stack ADT A Stack ADT is a list that allows only

More information

Stack ADT. ! push(x) puts the element x on top of the stack! pop removes the topmost element from the stack.

Stack ADT. ! push(x) puts the element x on top of the stack! pop removes the topmost element from the stack. STACK Stack ADT 2 A stack is an abstract data type based on the list data model All operations are performed at one end of the list called the top of the stack (TOS) LIFO (for last-in first-out) list is

More information

ADT: Lists, Stacks and Queues

ADT: Lists, Stacks and Queues H.O. #8 Fall 2015 Gary Chan ADT: Lists, Stacks and Queues N:6, 7, 8, 11 Outline List as an ADT Stacks An array-based implementation of lists Linked lists with pointer implementation Operations and implementations

More information

CSE 143 SAMPLE MIDTERM

CSE 143 SAMPLE MIDTERM CSE 143 SAMPLE MIDTERM 1. (5 points) In some methods, you wrote code to check if a certain precondition was held. If the precondition did not hold, then you threw an exception. This leads to robust code

More information

Stack Abstract Data Type

Stack Abstract Data Type Stacks Chapter 5 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop, peek, and empty To understand how Java implements a stack To learn how to implement a

More information

Lecture Data Structure Stack

Lecture Data Structure Stack Lecture Data Structure Stack 1.A stack :-is an abstract Data Type (ADT), commonly used in most programming languages. It is named stack as it behaves like a real-world stack, for example a deck of cards

More information

Common Misunderstandings from Exam 1 Material

Common Misunderstandings from Exam 1 Material Common Misunderstandings from Exam 1 Material Kyle Dewey Stack and Heap Allocation with Pointers char c = c ; char* p1 = malloc(sizeof(char)); char** p2 = &p1; Where is c allocated? Where is p1 itself

More information

Data Structures & Algorithm Analysis. Lecturer: Souad Alonazi

Data Structures & Algorithm Analysis. Lecturer: Souad Alonazi Data Structures & Algorithm Analysis Lec(3) Stacks Lecturer: Souad Alonazi What is a stack? Stores a set of elements in a particular order Stack principle: LAST IN FIRST OUT = LIFO It means: the last element

More information

Linear Data Structure

Linear Data Structure Linear Data Structure Definition A data structure is said to be linear if its elements form a sequence or a linear list. Examples: Array Linked List Stacks Queues Operations on linear Data Structures Traversal

More information

PRACTICE MIDTERM EXAM #2

PRACTICE MIDTERM EXAM #2 This practice exam is based on the actual midterm exam from Cynthia s Spring 2014 class. It did not include a classes problem (which you should expect this quarter), and the memory/pointers problem covered

More information

Trees. Carlos Moreno uwaterloo.ca EIT https://ece.uwaterloo.ca/~cmoreno/ece250

Trees. Carlos Moreno uwaterloo.ca EIT https://ece.uwaterloo.ca/~cmoreno/ece250 Carlos Moreno cmoreno @ uwaterloo.ca EIT-4103 https://ece.uwaterloo.ca/~cmoreno/ece250 Today's class: We'll discuss one possible implementation for trees (the general type of trees) We'll look at tree

More information

CSE 307: Principles of Programming Languages

CSE 307: Principles of Programming Languages 1 / 26 CSE 307: Principles of Programming Languages Names, Scopes, and Bindings R. Sekar 2 / 26 Topics Bindings 1. Bindings Bindings: Names and Attributes Names are a fundamental abstraction in languages

More information

Top of the Stack. Stack ADT

Top of the Stack. Stack ADT Module 3: Stack ADT Dr. Natarajan Meghanathan Professor of Computer Science Jackson State University Jackson, MS 39217 E-mail: natarajan.meghanathan@jsums.edu Stack ADT Features (Logical View) A List that

More information

Recursion. James Brucker

Recursion. James Brucker Recursion James Brucker What is Recursion? Recursion means for a function or method to call itself. A typical example of this is computing factorials: n! = n * (n-1)! Using recursion, we can compute n!

More information

IT 4043 Data Structures and Algorithms. Budditha Hettige Department of Computer Science

IT 4043 Data Structures and Algorithms. Budditha Hettige Department of Computer Science IT 4043 Data Structures and Algorithms Budditha Hettige Department of Computer Science 1 Syllabus Introduction to DSA Abstract Data Types List Operation Using Arrays Stacks Queues Recursion Link List Sorting

More information

Data Structure using C++ Lecture 04. Data Structures and algorithm analysis in C++ Chapter , 3.2, 3.2.1

Data Structure using C++ Lecture 04. Data Structures and algorithm analysis in C++ Chapter , 3.2, 3.2.1 Data Structure using C++ Lecture 04 Reading Material Data Structures and algorithm analysis in C++ Chapter. 3 3.1, 3.2, 3.2.1 Summary Stack Operations on a stack Representing stacks Converting an expression

More information

CSC 273 Data Structures

CSC 273 Data Structures CSC 273 Data Structures Lecture 3- Stacks Some familiar stacks What is a stack? Add item on top of stack Remove item that is topmost Last In, First Out LIFO Specifications of the ADT Stack Specifications

More information

Extra Credit: write mystrlen1 as a single function without the second parameter int mystrlen2(char* str)

Extra Credit: write mystrlen1 as a single function without the second parameter int mystrlen2(char* str) CPSC 122 Study Guide 3: Final Examination The final examination will consist of three parts: Part 1 covers mostly C++. For this, see study guides 1 and 2, exams 1 and 2, and part of exam 3, and quizzes

More information

10/26/2017 CHAPTER 3 & 4. Stacks & Queues. The Collection Framework

10/26/2017 CHAPTER 3 & 4. Stacks & Queues. The Collection Framework CHAPTER 3 & 4 Stacks & Queues The Collection Framework 1 Stack Abstract Data Type A stack is one of the most commonly used data structures in computer science A stack can be compared to a Pez dispenser

More information

Top of the Stack. Stack ADT

Top of the Stack. Stack ADT Module 3: Stack ADT Dr. Natarajan Meghanathan Professor of Computer Science Jackson State University Jackson, MS 39217 E-mail: natarajan.meghanathan@jsums.edu Stack ADT Features (Logical View) A List that

More information

Design Patterns in C++

Design Patterns in C++ Design Patterns in C++ Safety to exceptions Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa April 15, 2011 G. Lipari (Scuola Superiore Sant Anna) Exception Safety April 15,

More information

CSC 222: Computer Programming II. Spring 2005

CSC 222: Computer Programming II. Spring 2005 CSC 222: Computer Programming II Spring 2005 Stacks and recursion stack ADT push, pop, peek, empty, size ArrayList-based implementation, java.util.stack application: parenthesis/delimiter matching postfix

More information

Dynamic Data Structures

Dynamic Data Structures Dynamic Data Structures We have seen that the STL containers vector, deque, list, set and map can grow and shrink dynamically. We now examine how some of these containers can be implemented in C++. To

More information

Data Structures and Algorithms Notes

Data Structures and Algorithms Notes Data Structures and Algorithms Notes Notes by Winst Course taught by Dr. G. R. Baliga 256-400 ext. 3890 baliga@rowan.edu Course started: September 4, 2012 Last generated: December 18, 2013 Interfaces -

More information

Data Structures Week #3. Stacks

Data Structures Week #3. Stacks Data Structures Week #3 Stacks Outline Stacks Operations on Stacks Array Implementation of Stacks Linked List Implementation of Stacks Stack Applications October 5, 2015 Borahan Tümer, Ph.D. 2 Stacks (Yığınlar)

More information

Object Oriented Software Design - II

Object Oriented Software Design - II Object Oriented Software Design - II Safety to exceptions Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa April 12, 2012 G. Lipari (Scuola Superiore Sant Anna) Exception Safety

More information

Stack and Its Implementation

Stack and Its Implementation Stack and Its Implementation Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale tessema.mengistu@siu.edu Room - 3131 1 Definition of Stack Usage of Stack Outline

More information

EC8393FUNDAMENTALS OF DATA STRUCTURES IN C Unit 3

EC8393FUNDAMENTALS OF DATA STRUCTURES IN C Unit 3 UNIT 3 LINEAR DATA STRUCTURES 1. Define Data Structures Data Structures is defined as the way of organizing all data items that consider not only the elements stored but also stores the relationship between

More information

EE 368. Weeks 4 (Notes)

EE 368. Weeks 4 (Notes) EE 368 Weeks 4 (Notes) 1 Read Chapter 3 Recursion and Backtracking Recursion - Recursive Definition - Some Examples - Pros and Cons A Class of Recursive Algorithms (steps or mechanics about performing

More information

Programming for Engineers Pointers

Programming for Engineers Pointers Programming for Engineers Pointers ICEN 200 Spring 2018 Prof. Dola Saha 1 Pointers Pointers are variables whose values are memory addresses. A variable name directly references a value, and a pointer indirectly

More information

CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 10 October 1, 2018 CPSC 427, Lecture 10, October 1, 2018 1/20 Brackets Example (continued from lecture 8) Stack class Brackets class Main

More information

CS : Data Structures

CS : Data Structures CS 600.226: Data Structures Michael Schatz Sept 23, 2016 Lecture 9: Stacks Assignment 3: Due Sunday Sept 25 @ 10pm Remember: javac Xlint:all & checkstyle *.java & JUnit Solutions should be independently

More information

DataStruct 5. Stacks, Queues, and Deques

DataStruct 5. Stacks, Queues, and Deques 2013-2 DataStruct 5. Stacks, Queues, and Deques Michael T. Goodrich, et. al, Data Structures and Algorithms in C++, 2 nd Ed., John Wiley & Sons, Inc., 2011. October 30, 2013 Advanced Networking Technology

More information

COSC160: Data Structures: Lists and Queues. Jeremy Bolton, PhD Assistant Teaching Professor

COSC160: Data Structures: Lists and Queues. Jeremy Bolton, PhD Assistant Teaching Professor COSC160: Data Structures: Lists and Queues Jeremy Bolton, PhD Assistant Teaching Professor Outline I. Queues I. FIFO Queues I. Usage II. Implementations II. LIFO Queues (Stacks) I. Usage II. Implementations

More information

Linear Structures. Linear Structure. Implementations. Array details. List details. Operations 2/10/2013

Linear Structures. Linear Structure. Implementations. Array details. List details. Operations 2/10/2013 Linear Structure Linear Structures Chapter 4 CPTR 318 Every non-empty linear structure has A unique element called first A unique element called last Every element except last has a unique successor Every

More information

Exception Namespaces C Interoperability Templates. More C++ David Chisnall. March 17, 2011

Exception Namespaces C Interoperability Templates. More C++ David Chisnall. March 17, 2011 More C++ David Chisnall March 17, 2011 Exceptions A more fashionable goto Provides a second way of sending an error condition up the stack until it can be handled Lets intervening stack frames ignore errors

More information

C++ Templates. David Camp

C++ Templates. David Camp C++ Templates David Camp C Marcos #define () #define min(i, j) (((i) < (j))? (i) : (j)) #define max(i, j) (((i) > (j))? (i) : (j)) #define RADTODEG(x)

More information

Stacks. Revised based on textbook author s notes.

Stacks. Revised based on textbook author s notes. Stacks Revised based on textbook author s notes. Stacks A restricted access container that stores a linear collection. Very common for solving problems in computer science. Provides a last-in first-out

More information

CS24 Week 4 Lecture 2

CS24 Week 4 Lecture 2 CS24 Week 4 Lecture 2 Kyle Dewey Overview Linked Lists Stacks Queues Linked Lists Linked Lists Idea: have each chunk (called a node) keep track of both a list element and another chunk Need to keep track

More information

Lecture 14. Arrays II. Selection Sort & Parallel Arrays. CptS 121 Summer 2016 Armen Abnousi

Lecture 14. Arrays II. Selection Sort & Parallel Arrays. CptS 121 Summer 2016 Armen Abnousi Lecture 14 Arrays II Selection Sort & Parallel Arrays CptS 121 Summer 2016 Armen Abnousi Sorting an array We have seen how to search in an array Often we want to sort our arrays for more efficient future

More information

Stacks. 1 Introduction. 2 The Stack ADT. Prof. Stewart Weiss. CSci 235 Software Design and Analysis II Stacks

Stacks. 1 Introduction. 2 The Stack ADT. Prof. Stewart Weiss. CSci 235 Software Design and Analysis II Stacks 1 Introduction are probably the single most important data structure of computer science. They are used across a broad range of applications and have been around for more than fty years, having been invented

More information

CS 211 Programming Practicum Spring 2018

CS 211 Programming Practicum Spring 2018 Due: Thursday, 4/5/18 at 11:59 pm Infix Expression Evaluator Programming Project 5 For this lab, write a C++ program that will evaluate an infix expression. The algorithm REQUIRED for this program will

More information

March 13/2003 Jayakanth Srinivasan,

March 13/2003 Jayakanth Srinivasan, Statement Effort MergeSort(A, lower_bound, upper_bound) begin T(n) if (lower_bound < upper_bound) Θ(1) mid = (lower_bound + upper_bound)/ 2 Θ(1) MergeSort(A, lower_bound, mid) T(n/2) MergeSort(A, mid+1,

More information

Lists are great, but. Stacks 2

Lists are great, but. Stacks 2 Stacks Lists are great, but Lists are simply collections of items Useful, but nice to have some meaning to attach to them Restrict operations to create useful data structures We want to have ADTs that

More information

Stacks. The unorganized person s data structure. stacks 1

Stacks. The unorganized person s data structure. stacks 1 Stacks The unorganized person s data structure stacks 1 Stack characteristics Entries are ordered in terms of access -- both insertion and removal take place at same spot (top of stack) Specialized type

More information

Backtracking. Module 6. The Eight Queens Problem. CS 147 Sam Houston State University Dr. McGuire. Backtracking. Recursion Revisited

Backtracking. Module 6. The Eight Queens Problem. CS 147 Sam Houston State University Dr. McGuire. Backtracking. Recursion Revisited Module 6 Recursion Revisited CS 147 Sam Houston State University Dr. McGuire Backtracking Backtracking A strategy for guessing at a solution and backing up when an impasse is reached Recursion and backtracking

More information

Stacks and Queues. David Greenstein Monta Vista

Stacks and Queues. David Greenstein Monta Vista Stacks and Queues David Greenstein Monta Vista Stack vs Queue Stacks and queues are used for temporary storage, but in different situations Stacks are Used for handling nested structures: processing directories

More information

www.thestudycampus.com Recursion Recursion is a process for solving problems by subdividing a larger problem into smaller cases of the problem itself and then solving the smaller, more trivial parts. Recursion

More information

Lecture Notes 4 More C++ and recursion CSS 501 Data Structures and Object-Oriented Programming Professor Clark F. Olson

Lecture Notes 4 More C++ and recursion CSS 501 Data Structures and Object-Oriented Programming Professor Clark F. Olson Lecture Notes 4 More C++ and recursion CSS 501 Data Structures and Object-Oriented Programming Professor Clark F. Olson Reading for this lecture: Carrano, Chapter 2 Copy constructor, destructor, operator=

More information

System-on-Chip (SOC) 晶 系統組

System-on-Chip (SOC) 晶 系統組 專題 學程說明會 System-on-Chip (SOC) 晶 系統組 葉經緯 王進賢 朱元三 蔡宗亨 崇勛 林柏宏 What s hot in your life? More Deeply! Information Navigation Social Activity Translation Face Recognition - Searching SoC Applications Consumer

More information

double d0, d1, d2, d3; double * dp = new double[4]; double da[4];

double d0, d1, d2, d3; double * dp = new double[4]; double da[4]; All multiple choice questions are equally weighted. You can generally assume that code shown in the questions is intended to be syntactically correct, unless something in the question or one of the answers

More information

ECE Fall st Midterm Examination (120 Minutes, closed book)

ECE Fall st Midterm Examination (120 Minutes, closed book) ECE Fall 2009 1 st Midterm Examination (120 Minutes, closed book) Name: Question Score Student ID: 1 (15) 2 (20) 3 (20) 4 (15) 5 (20) 6 (10) NOTE: Any questions on writing code must be answered in Java

More information

Backtracking. The Eight Queens Problem. The Eight Queens Problem. The Eight Queens Problem. The Eight Queens Problem. Chapter 5

Backtracking. The Eight Queens Problem. The Eight Queens Problem. The Eight Queens Problem. The Eight Queens Problem. Chapter 5 Chapter 5 Recursion as a Problem-Solving Technique Backtracking Backtracking A strategy for guessing at a solution and backing up when an impasse is reached Recursion and backtracking can be combined to

More information

! A data type for which: ! In fact, an ADT may be implemented by various. ! Examples:

! A data type for which: ! In fact, an ADT may be implemented by various. ! Examples: Ch. 8: ADTs: Stacks and Queues Abstract Data Type A data type for which: CS 8 Fall Jill Seaman - only the properties of the data and the operations to be performed on the data are specific, - not concerned

More information

ADT Stack. Inserting and deleting elements occurs at the top of Stack S. top. bottom. Stack S

ADT Stack. Inserting and deleting elements occurs at the top of Stack S. top. bottom. Stack S Stacks Stacks & Queues A linear sequence, or list, is an ordered collection of elements: S = (s 1, s 2,..., s n ) Stacks and queues are finite linear sequences. A Stack is a LIFO (Last In First Out) list.

More information

CS 211 Programming Practicum Fall 2018

CS 211 Programming Practicum Fall 2018 Due: Wednesday, 11/7/18 at 11:59 pm Infix Expression Evaluator Programming Project 5 For this lab, write a C++ program that will evaluate an infix expression. The algorithm REQUIRED for this program will

More information

ADTs Stack and Queue. Outline

ADTs Stack and Queue. Outline Chapter 5 ADTs Stack and Queue Fall 2017 Yanjun Li CS2200 1 Outline Stack Array-based Implementation Linked Implementation Queue Array-based Implementation Linked Implementation Comparison Fall 2017 Yanjun

More information

Networked Embedded System Patterns for C Developers. Overview of C (& C++) Programming Styles. Douglas C. Schmidt

Networked Embedded System Patterns for C Developers. Overview of C (& C++) Programming Styles. Douglas C. Schmidt Networked Embedded System Patterns for C Developers Part II: Professor Department of EECS d.schmidt@vanderbilt.edu Vanderbilt University www.dre.vanderbilt.edu/ schmidt/ (615) 343-8197 June 3, 2009 Motivation

More information