Chapter 3: Lists, Stacks, and Queues Abstract Data Types Lists and Sorted Lists CS 340 Page 34 Stacks and Stack Applications Queues and Queue Applications.

Slides:



Advertisements
Similar presentations
Stacks, Queues, and Linked Lists
Advertisements

1111 Abstract Data Types Cpt S 223. School of EECS, WSU.
DATA STRUCTURES USING C++ Chapter 5
Chapter 3 – Lists A list is just what the name implies, a finite, ordered sequence of items. Order indicates each item has a position. A list of size 0.
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.
CS 240Chapter 6 - StacksPage 21 Chapter 6 Stacks The stack abstract data type is essentially a list using the LIFO (last-in-first-out) policy for adding.
Chapter 6: Stacks STACK APPLICATIONS STACK IMPLEMENTATIONS CS
Lecture 5 Sept 15 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Stacks CS 3358 – Data Structures. What is a stack? It is an ordered group of homogeneous items of elements. Elements are added to and removed from the.
1 Chapter 24 Lists Stacks and Queues. 2 Objectives F To design list with interface and abstract class (§24.2). F To design and implement a dynamic list.
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.
CS 340Chapter 3: Lists, Stacks, and Queues1 Abstract Data Types An ADT is a set of operations upon a set of data. Implementation details are not specified.
Lecture 6 Feb 12 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Main Index Contents 11 Main Index Contents Container Types Container Types Sequence Containers Sequence Containers Associative Containers Associative Containers.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 12 – Data Structures Outline 12.1Introduction.
Chapter 4 Linked Lists. © 2005 Pearson Addison-Wesley. All rights reserved4-2 Preliminaries Options for implementing an ADT List –Array has a fixed size.
1 Chapter 6 Lists Plus. ADT Sorted List Operations Transformers n MakeEmpty n InsertItem n DeleteItem Observers n IsFull n LengthIs n RetrieveItem Iterators.
Data Structures Using C++ 2E
Implementing Stacks Ellen Walker CPSC 201 Data Structures Hiram College.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 8 Stacks and Queues Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
2 Preliminaries Options for implementing an ADT List Array has a fixed size Data must be shifted during insertions and deletions Linked list is able to.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
Lists ADT (brief intro):  Abstract Data Type  A DESCRIPTION of a data type  The data type can be anything: lists, sets, trees, stacks, etc.  What.
C++ Classes and Data Structures Jeffrey S. Childs
1 CSC 222: Computer Programming II Spring 2004 Pointers and linked lists  human chain analogy  linked lists: adding/deleting/traversing nodes  Node.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
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.
INTRODUCTION TO BINARY TREES P SORTING  Review of Linear Search: –again, begin with first element and search through list until finding element,
1 Linked Stack Chapter 4. 2 Linked Stack We can implement a stack as a linked list. Same operations. No fixed maximum size. Stack can grow indefinitely.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 17: Linked Lists.
1 Chapter 16 Linked Structures Dale/Weems. 2 Chapter 16 Topics l Meaning of a Linked List l Meaning of a Dynamic Linked List l Traversal, Insertion and.
1 Chapter 16 Linked Structures Dale/Weems/Headington.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 16. Linked Lists.
1 Linked-list, stack and queue. 2 Outline Abstract Data Type (ADT)‏ Linked list Stack Queue.
Iterator for linked-list traversal, Template & STL COMP171 Fall 2005.
Copyright © 2012 Pearson Education, Inc. Chapter 17: Linked Lists.
OOP using C Abstract data types How to accomplish the task??? Requirements Details Input, output, process Specify each task in terms of input.
12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 9 An Introduction.
1 CSC 222: Computer Programming II Spring 2004 Stacks and recursion  stack ADT  push, pop, top, empty, size  vector-based implementation, library 
1 Chapter 3 Lists, Stacks, and Queues Reading: Sections 3.1, 3.2, 3.3, 3.4 Abstract Data Types (ADT) Iterators Implementation of Vector.
11/07/141 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: –Data stored –Operations on the.
CS 240Chapter 10 – TreesPage Chapter 10 Trees The tree abstract data type provides a hierarchical to the representation of certain types of relationships.
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.
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.
STACKS & QUEUES for CLASS XII ( C++).
Cpt S 122 – Data Structures Abstract Data Types
Data Structure By Amee Trivedi.
Chapter 12 – Data Structures
Lists CS 3358.
CS 1114: Implementing Search
Homework 4 questions???.
Chapter 4 Linked Lists.
Cinda Heeren / Geoffrey Tien
Stack.
Chapter 4 Linked Lists
Doubly linked lists.
Stack Lesson xx   This module shows you the basic elements of a type of linked list called a stack.
CMSC 341 Lecture 5 Stacks, Queues
Chapter 16-2 Linked Structures
Linked Lists.
5.4 Additional Stack Applications
[Chapter 4; Chapter 6, pp ] CSC 143 Linked Lists [Chapter 4; Chapter 6, pp ]
Chapter 16 Linked Structures
Pointers & Dynamic Data Structures
Chapter 3 Lists, Stacks, and Queues
Presented by : Aman Gupta PGT CS KV No.1, Narimedu, Madurai
Presentation transcript:

Chapter 3: Lists, Stacks, and Queues Abstract Data Types Lists and Sorted Lists CS 340 Page 34 Stacks and Stack Applications Queues and Queue Applications

CS 340 Page 35 Abstract Data Types An ADT is a set of operations upon a set of data. Implementation details are not specified in an ADT. The program designer determines the operations that are needed and the specific data that will be used in the implementation. The implementation of the ADT should be easy to modify, and such modifications should be transparent to any code deploying the ADT.

CS 340 Page 36 ADT #1: The List A list is a finite ordered collection of items of the same type. Common list operations include: Emptying the entire list Determining whether the list is empty Determining the size of the list Determining the location of a particular list element Determining the value of an element at a particular location in the list Inserting a new list element at a particular location Removing a particular element from the list Outputting the entire list

CS 340 Page 37 An Array Implementation’s Performance List Implementation Option: Array a1a1a1a1 a1a1a1a1 a2a2a2a2 a2a2a2a2 a3a3a3a3 a3a3a3a3 :: a n-2 a n-1 anananan anananan ?? ?? :: ?? nn Problems with the array implementation: –Data movement really slows down insertions to and removals from the list –The maximum list size must be specified Emptying the list O(1) Determining if the list is empty O(1) Determining the size of the list O(1) Determining the location of a particular element O(n) Determining the value of an element in a particular location O(1) Inserting a new element into a particular location O(n) Removing a particular element O(n) Outputting the list O(n)

CS 340 Page 38 A Linked List Implementation’s Performance List Implementation Option: Linked List Problems with the linked list implementation: –Pointers consume memory not needed with arrays –Lack of indexing necessitates repeated list traversals (e.g., binary search is impossible) a1a1a1a1 a1a1a1a1 a2a2a2a2 a2a2a2a2 a3a3a3a3 a3a3a3a3 :: a n-2 a n-1 anananan anananan Emptying the list O(n) Determining if the list is empty O(1) Determining the size of the list O(n) Determining the location of a particular element O(n) Determining the value of an element in a particular location O(n) Inserting a new element into a particular location O(1) Removing a particular element O(1) Outputting the list O(n)

CS 340 Page 39 #ifndef LIST_H #include template class list { protected: struct node { Etype element; node *next; node(Etype e = 0, node *n = NULL) : element(e), next(n) {} }; node *head; node *current; void deleteList(); public: list(): head(new node), current(head) {} virtual ~list() { deleteList(); } const list& operator = (list &value); const list& operator ++ (); bool operator ! () const; const Etype& operator () () const; bool isEmpty() const { return (head->next == NULL); } virtual bool find(const Etype &x); virtual bool findPrevious(const Etype &x); void first() { if (head->next != NULL) current = head->next; } void header() { current = head; } bool remove(const Etype &x); virtual void insert(const Etype &x); virtual void insertAsFirstElement(const Etype &x); }; #ifndef LIST_H #include template class list { protected: struct node { Etype element; node *next; node(Etype e = 0, node *n = NULL) : element(e), next(n) {} }; node *head; node *current; void deleteList(); public: list(): head(new node), current(head) {} virtual ~list() { deleteList(); } const list& operator = (list &value); const list& operator ++ (); bool operator ! () const; const Etype& operator () () const; bool isEmpty() const { return (head->next == NULL); } virtual bool find(const Etype &x); virtual bool findPrevious(const Etype &x); void first() { if (head->next != NULL) current = head->next; } void header() { current = head; } bool remove(const Etype &x); virtual void insert(const Etype &x); virtual void insertAsFirstElement(const Etype &x); }; Linked List Implementation in Visual C++ Class Template StructureStructure Structure Constructor Class Constructor Class Destructor Virtual Function: Derived classes may have their own version of this function Constant Return: Value returned is treated as a constant Constant Constant Modifier: This operator accesses but doesn’t modify In-Line Code

CS 340 Page 40 // Member function to free all memory associated with the linked list. template void list :: deleteList() { node *p = head->next; node *temp; while (p != NULL) { temp = p->next; delete p; p = temp; } delete head; } // Assignment operator: duplicates parameterized linked list. template inline const list & list :: operator = (list &value) { if (this == &value) return *this; deleteList(); current = head = new node; for (value.first(); !value; ++value) { current->next = new node(value(), current->next); current = current->next; } current->next = NULL; first(); value.first(); return *this; } // Member function to free all memory associated with the linked list. template void list :: deleteList() { node *p = head->next; node *temp; while (p != NULL) { temp = p->next; delete p; p = temp; } delete head; } // Assignment operator: duplicates parameterized linked list. template inline const list & list :: operator = (list &value) { if (this == &value) return *this; deleteList(); current = head = new node; for (value.first(); !value; ++value) { current->next = new node(value(), current->next); current = current->next; } current->next = NULL; first(); value.first(); return *this; } In-Line Function: Prompts the compiler to generate code inline instead of laying it down once and calling it through the usual mechanisms, improving performance for functions that do little but are called often

CS 340 Page 41 // Increment operator: moves current pointer to next node (if possible). template inline const list & list :: operator ++ () { if (current != NULL) current = current->next; return *this; } // Logical “not” operator: indicates whether current pointer is non-NULL. template inline bool list :: operator ! () const { return (current != NULL); } // Parenthetical operator: returns value of current node (or head node if current is NULL). template inline const Etype& list :: operator () () const { if (current != NULL) return current->element; else return head->element; } // Increment operator: moves current pointer to next node (if possible). template inline const list & list :: operator ++ () { if (current != NULL) current = current->next; return *this; } // Logical “not” operator: indicates whether current pointer is non-NULL. template inline bool list :: operator ! () const { return (current != NULL); } // Parenthetical operator: returns value of current node (or head node if current is NULL). template inline const Etype& list :: operator () () const { if (current != NULL) return current->element; else return head->element; }

CS 340 Page 42 // Member function to determine whether parameterized element is in list. template bool list :: find(const Etype &x) { node *p; for (p = head->next; p != NULL; p = p->next) { if (p->element == x) { current = p; return true; } return false; } // Member function to locate predecessor of parameterized value in list. template bool list :: findPrevious(const Etype &x) { node *p; for (p = head; p->next != NULL; p = p->next) { if (p->next->element == x) { current = p; return true; } return false; } // Member function to determine whether parameterized element is in list. template bool list :: find(const Etype &x) { node *p; for (p = head->next; p != NULL; p = p->next) { if (p->element == x) { current = p; return true; } return false; } // Member function to locate predecessor of parameterized value in list. template bool list :: findPrevious(const Etype &x) { node *p; for (p = head; p->next != NULL; p = p->next) { if (p->next->element == x) { current = p; return true; } return false; }

CS 340 Page 43 // Member function to remove first occurrence of parameterized value from list. template bool list :: remove(const Etype &x) { node *cellToDelete; if (findPrevious(x)) { cellToDelete = current->next; current->next = cellToDelete->next; delete cellToDelete; return true; } return false; } // Member function to insert parameterized value after current node in list. template void list :: insert(const Etype &x) { node *p = new node(x, current->next); if (p != NULL) { current->next = p; current = current->next; } // Member function to insert parameterized value as new head element in list. template void list :: insertAsFirstElement(const Etype &x) { header(); insert(x); } #define LIST_H #endif // Member function to remove first occurrence of parameterized value from list. template bool list :: remove(const Etype &x) { node *cellToDelete; if (findPrevious(x)) { cellToDelete = current->next; current->next = cellToDelete->next; delete cellToDelete; return true; } return false; } // Member function to insert parameterized value after current node in list. template void list :: insert(const Etype &x) { node *p = new node(x, current->next); if (p != NULL) { current->next = p; current = current->next; } // Member function to insert parameterized value as new head element in list. template void list :: insertAsFirstElement(const Etype &x) { header(); insert(x); } #define LIST_H #endif

CS 340 Page 44 #include "List.h" #include using namespace std; void printList(list &lst); // The main function generates a couple of integer lists // to test the functionality of the linked list class. void main() { list lst1, lst2; cout << "(This should be empty)" << endl; printList(lst1); for (int i = 1; i <= 5; i++) lst1.insertAsFirstElement(i); cout << "(This should be )" << endl; printList(lst1); for (int i = 4; i <= 6; i++) if (lst1.find(i)) cout << "Found " << lst1() << endl; else cout << i << " not found" << endl; lst2 = lst1; cout << "(This should be )" << endl; printList(lst2); lst2.remove(3); cout << "(This should be )" << endl; printList(lst2); cout << "(but this should still be )" << endl; printList(lst1); } #include "List.h" #include using namespace std; void printList(list &lst); // The main function generates a couple of integer lists // to test the functionality of the linked list class. void main() { list lst1, lst2; cout << "(This should be empty)" << endl; printList(lst1); for (int i = 1; i <= 5; i++) lst1.insertAsFirstElement(i); cout << "(This should be )" << endl; printList(lst1); for (int i = 4; i <= 6; i++) if (lst1.find(i)) cout << "Found " << lst1() << endl; else cout << i << " not found" << endl; lst2 = lst1; cout << "(This should be )" << endl; printList(lst2); lst2.remove(3); cout << "(This should be )" << endl; printList(lst2); cout << "(but this should still be )" << endl; printList(lst1); } A Test Driver For The Linked List Implementation

CS 340 Page 45 // The printList function outputs the contents // of the linked list, starting at the head. void printList(list &lst) { if (lst.isEmpty()) cout << "Empty list." << endl; else for (lst.first(); !lst; ++lst) cout << lst() << endl; } // The printList function outputs the contents // of the linked list, starting at the head. void printList(list &lst) { if (lst.isEmpty()) cout << "Empty list." << endl; else for (lst.first(); !lst; ++lst) cout << lst() << endl; }

CS 340 Page 46 Inheritance: The sortedList Class If Etype values can be sorted, then the list class can be modified to accommodate this sorting. This can be easily accomplished by deriving a subclass of list, and overriding the two insertion functions insert and insertAsFirstElement. #include "List.h" template class sortedList: public list { public: virtual void insert(const Etype &x); virtual void insertAsFirstElement(const Etype &x) { insert(x); } } // This member function inserts the parameterized // value and preserves the sorted nature of the list. template void sortedList :: insert(const Etype &x) { for (node *p = head; p->next != NULL; p = p->next) { if (p->next->element > x) { current = p; break; } list ::insert(x); } #include "List.h" template class sortedList: public list { public: virtual void insert(const Etype &x); virtual void insertAsFirstElement(const Etype &x) { insert(x); } } // This member function inserts the parameterized // value and preserves the sorted nature of the list. template void sortedList :: insert(const Etype &x) { for (node *p = head; p->next != NULL; p = p->next) { if (p->next->element > x) { current = p; break; } list ::insert(x); }

CS 340 Page 47 #include "SortedList.h" #include using namespace std; void printList(list &lst); // The main function generates a couple of integer lists // to test the functionality of the linked list class. void main() { sortedList lst1, lst2; cout << "(This should be empty)" << endl; printList(lst1); for (int i = 1; i <= 5; i++) lst1.insertAsFirstElement(i); cout << "(This should be )" << endl; printList(lst1); for (int i = 4; i <= 6; i++) if (lst1.find(i)) cout << "Found " << lst1() << endl; else cout << i << " not found" << endl; lst2 = lst1; cout << "(This should be )" << endl; printList(lst2); lst2.remove(3); cout << "(This should be )" << endl; printList(lst2); cout << "(but this should still be )" << endl; printList(lst1); } #include "SortedList.h" #include using namespace std; void printList(list &lst); // The main function generates a couple of integer lists // to test the functionality of the linked list class. void main() { sortedList lst1, lst2; cout << "(This should be empty)" << endl; printList(lst1); for (int i = 1; i <= 5; i++) lst1.insertAsFirstElement(i); cout << "(This should be )" << endl; printList(lst1); for (int i = 4; i <= 6; i++) if (lst1.find(i)) cout << "Found " << lst1() << endl; else cout << i << " not found" << endl; lst2 = lst1; cout << "(This should be )" << endl; printList(lst2); lst2.remove(3); cout << "(This should be )" << endl; printList(lst2); cout << "(but this should still be )" << endl; printList(lst1); } A Test Driver For The Sorted List Implementation // The printList function outputs the contents // of the linked list, starting at the head. void printList(list &lst) { if (lst.isEmpty()) cout << "Empty list." << endl; else for (lst.first(); !lst; ++lst) cout << lst() << endl; } // The printList function outputs the contents // of the linked list, starting at the head. void printList(list &lst) { if (lst.isEmpty()) cout << "Empty list." << endl; else for (lst.first(); !lst; ++lst) cout << lst() << endl; }

CS 340 Page 48 Example List Application: Polynomials Let Etype be a two-field structure containing the coefficient and exponent of each monomial within the polynomial. Sort the nodes comprising each polynomial based upon the values of their exponents. Polynomial p 1 (x) = 35x 6 - 7x x Polynomial p 2 (x) = -3x x 3 - 4x The operations for this ADT could include: Addition, subtraction, and multiplication of polynomials Derivatives of polynomials Evaluation of polynomials (i.e., plugging in values)

CS 340 Page 49 STL List Alternative #1: vector The C++ Standard Template Library provides a built-in implementation of a list ADT: the vector. #include using namespace std; void printVector(vector &vec); // The main function generates two integer lists // to test the functionality of the vector class. void main() { vector vec1, vec2; cout << "(This should be empty)" << endl; printVector(vec1); vector ::iterator itr = vec1.begin(); for (int i = 1; i <= 5; i++) itr = vec1.insert(itr, i); cout << "(This should be )" << endl; printVector(vec1); for (int val = 4; val <= 6; val++) { int i = 0; bool found = false; while ( (i < vec1.size()) && (!found) ) if (vec1.at(i) == val) { found = true; cout << "Found " << val << endl; } else i++; if (!found) cout << val << " not found" << endl; } vec2 = vec1; cout << "(This should be )" << endl; printVector(vec2); for (vector ::iterator itr = vec2.begin(); itr != vec2.end(); itr++) if (*itr == 3) itr = vec2.erase(itr); #include using namespace std; void printVector(vector &vec); // The main function generates two integer lists // to test the functionality of the vector class. void main() { vector vec1, vec2; cout << "(This should be empty)" << endl; printVector(vec1); vector ::iterator itr = vec1.begin(); for (int i = 1; i <= 5; i++) itr = vec1.insert(itr, i); cout << "(This should be )" << endl; printVector(vec1); for (int val = 4; val <= 6; val++) { int i = 0; bool found = false; while ( (i < vec1.size()) && (!found) ) if (vec1.at(i) == val) { found = true; cout << "Found " << val << endl; } else i++; if (!found) cout << val << " not found" << endl; } vec2 = vec1; cout << "(This should be )" << endl; printVector(vec2); for (vector ::iterator itr = vec2.begin(); itr != vec2.end(); itr++) if (*itr == 3) itr = vec2.erase(itr); cout << "(This should be )" << endl; printVector(vec2); cout << "(but this should still be )" << endl; printVector(vec1); } // The printVector function outputs the entire // contents of the vector. void printVector(vector &vec) { if (vec.empty()) cout << "Empty vector." << endl; else for (vector ::iterator itr = vec.begin(); itr != vec.end(); itr++) cout << *itr << endl; } cout << "(This should be )" << endl; printVector(vec2); cout << "(but this should still be )" << endl; printVector(vec1); } // The printVector function outputs the entire // contents of the vector. void printVector(vector &vec) { if (vec.empty()) cout << "Empty vector." << endl; else for (vector ::iterator itr = vec.begin(); itr != vec.end(); itr++) cout << *itr << endl; } The Good News Like arrays, vectors are indexable in constant time. The Good News Like arrays, vectors are indexable in constant time. The Bad News Insertion and removal is expensive, except at the end of the vector. The Bad News Insertion and removal is expensive, except at the end of the vector.

CS 340 Page 50 STL List Alternative #2: list The C++ STL also provides a second built- in implementation of a list ADT: the list. #include using namespace std; void printList(list &lst); // The main function generates two integer lists // to test the functionality of the list class. void main() { list lst1, lst2; cout << "(This should be empty)" << endl; printList(lst1); for (int i = 1; i <= 5; i++) lst1.push_front(i); cout << "(This should be )" << endl; printList(lst1); for (int val = 4; val <= 6; val++) { list ::iterator itr = lst1.begin(); bool found = false; while ( (itr != lst1.end()) && (!found) ) if (*itr == val) { found = true; cout << "Found " << val << endl; } else itr++; if (!found) cout << val << " not found" << endl; } lst2 = lst1; cout << "(This should be )" << endl; printList(lst2); for (list ::iterator itr = lst2.begin(); itr != lst2.end(); itr++) if (*itr == 3) itr = lst2.erase(itr); #include using namespace std; void printList(list &lst); // The main function generates two integer lists // to test the functionality of the list class. void main() { list lst1, lst2; cout << "(This should be empty)" << endl; printList(lst1); for (int i = 1; i <= 5; i++) lst1.push_front(i); cout << "(This should be )" << endl; printList(lst1); for (int val = 4; val <= 6; val++) { list ::iterator itr = lst1.begin(); bool found = false; while ( (itr != lst1.end()) && (!found) ) if (*itr == val) { found = true; cout << "Found " << val << endl; } else itr++; if (!found) cout << val << " not found" << endl; } lst2 = lst1; cout << "(This should be )" << endl; printList(lst2); for (list ::iterator itr = lst2.begin(); itr != lst2.end(); itr++) if (*itr == 3) itr = lst2.erase(itr); cout << "(This should be )" << endl; printList(lst2); cout << "(but this should still be )" << endl; printList(lst1); } // The printList function outputs the entire // contents of the vector. void printList(list &lst) { if (lst.empty()) cout << "Empty list." << endl; else for (list ::iterator itr = lst.begin(); itr != lst.end(); itr++) cout << *itr << endl; } cout << "(This should be )" << endl; printList(lst2); cout << "(but this should still be )" << endl; printList(lst1); } // The printList function outputs the entire // contents of the vector. void printList(list &lst) { if (lst.empty()) cout << "Empty list." << endl; else for (list ::iterator itr = lst.begin(); itr != lst.end(); itr++) cout << *itr << endl; } The Good News Insertion and removal at any known position is inexpensive. The Good News Insertion and removal at any known position is inexpensive. The Bad News Like traditional linked lists, this doubly linked list is not easily indexable.

CS 340 Page 51 ADT #2: The Stack A stack is a list in which insertions and removals can only transpire at one end of the list, i.e., the top of the stack.               stk.pop( ) stk.push(  )

CS 340 Page 52 Example Stack Application: Arithmetic Expressions Stacks can be used to convert infix expressions into postfix expressions Following these rules, then, the infix expression * ( / 2 ) is converted into the postfix expression / + * - When this is encountered in an infix expression... … then do this! the beginning of the infix expression push a # onto the stack an operand append it to the postfix expression a right parenthesis repeatedly pop the stack, appending each entry to the postfix expression, until a left parenthesis is popped (but not output) the end of the infix expression repeatedly pop the stack, adding each entry to the expression a left parenthesis push it onto the stack a * or / operator repeatedly pop the stack, appending all popped * and / operators to the end of the postfix expression, until something else is popped; push this last item back onto the stack, followed by the new * or / that was encountered a + or - operator repeatedly pop the stack, appending all popped +, -, *, and / operators to the end of the postfix expression, until something else is popped; push this last item back onto the stack, followed by the new + or - that was encountered

CS 340 Page 53 Arithmetic Expression Evaluation (continued) Then a separate stack can be used to evaluate the postfix expression Following these rules with the postfix expression / + * - yields: When this is encountered in a postfix expression... … then do this! an operandpush it onto the stack An operator pop the stack twice, perform the operation on the two popped operands, and push the result back onto the stack the end of the postfix expression pop the stack once; the popped value is the final result

CS 340 Page 54 Example Stack Application: The Run-Time Stack Stores local data and call information for nested procedures in a program Grows downward from its origin Stack pointer points to current topmost data item on the stack Push operation decrements pointer and copies data to stack Pop operation copies data from stack and then increments pointer Each procedure called in the program stores procedure return information (in yellow) and local data (in other colors) by pushing them onto stack

CS 340 Page 55 Stack Implementation Alternatives An Array Implementation –Positives Trivial implementation due to indexing –Negatives Size must be declared in advance A Linked List Implementation –Positives Dynamically allocates the right amount of memory Straightforward (if not quite trivial) implementation –Negatives Wastes memory for pointers that are underutilized

CS 340 Page 56 ADT #3: The Queue   que.dequeue( )  que.enqueue(  )  A queue is a list in which insertions can only occur at one end of the list (the front of the queue) and removals can only occur at the opposite end of the list (the back of the queue).

CS 340 Page 57 Example Queue Application: Server Access The “first-come, first-served” nature of the queue ADT can be adapted to providing orderly access to file servers, print servers, Web servers, etc. Moe’sPrint Job #1 Moe’sPrint Larry’sPrint Larry’sPrint Moe’sPrint Job #2 Moe’sPrint Curly’sPrint Job #1 Curly’sPrint

CS 340 Page 58 Example Queue Application: Breadth-First Search bfs(v) enqueue(v) enqueue(v) while queue not empty while queue not empty v=dequeue() v=dequeue() process(v) process(v) for all unvisited vertices i adjacent to v for all unvisited vertices i adjacent to v mark i as visited mark i as visited enqueue(i) enqueue(i) Search a tree structure for a goal, beginning at the root node and exploring all neighboring nodes Use a queue to remember which nodes have yet to be fully explored If the queue is ever empty without the goal being found, then the goal isn’t in the tree

CS 340 Page 59 Queue Implementation Alternatives An Array Implementation –Positives Straightforward implementation due to indexing –Negatives Size must be declared in advance Wraparound is needed to avoid false overflows A Linked List Implementation –Positives Dynamically allocates the right amount of memory Wraparound problem is circumvented –Negatives Wastes memory for pointers that are underutilized