Download presentation
Presentation is loading. Please wait.
Published byAlfred Bruce Modified over 9 years ago
1
Exam Review 5/28/15
2
Software Development (Review) Make it work…then make it pretty can result in dangerous code Better to take a unified, consistent and logical approach 5 Phases of the Software Development Lifecycle: 1. Requirements 2. Design 3. Implementation 4. Testing/Integration 5. Maintenance Waterfall Method Agile/SCRUM Method Prototyping Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 2
3
Software Development (Review ctd) Need to decide what the actual problem is (which may or may not be what the customer/user asked for) How to approach: Top Down Design Original problem divided into smaller, more manageable specific problems Object Oriented Design Identify objects, their attributes and operations Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 3
4
Abstract Data Type (ADT)…review An abstract data type is: 1. A collection of data items (storage structures) 2. Basic operations that can be performed on these items (algorithms) Called abstract because the represented data and the algorithms that operate on it are independent of the implementation (data abstraction) Thinking about what can be done with the data, not how it is done
5
Lists (Review) Properties of a list: Homogeneous Finite length Sequential elements Basic Operations for a List Class: Constructor empty() insert() delete() display() Implementation involves Defining data members Defining function members from design phase Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 5
6
Using a Template? (Review) By writing ‘template’ before a class definition, the class can be used with any data type Allows for flexibility/versatility Template could use any data type represented by T T can be any of C++ defined data types (int, char, etc) or one that is user-defined Different ways to implement a template, can declare and implement in one.h file Better approach is to have template class definition in header file and implementation in it’s own.cpp file In this instance, will need to add the line: Template before each function header Each function name is preceded with classname :: Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 6
7
Array-Based Implementation of Lists (Review) An array is a viable choice for storing list elements Element are sequential It is a commonly available data type Algorithm development is easy Normally sequential orderings of list elements match with array elements 7
8
List Class with Static Array (Review) Use template template class List { public: List(); bool isEmpty() const; bool insert(const T&, const int&); bool remove(const int&); void display(ostream&) const; private: T _items[CAPACITY]; // array to store list elements int _size; // current size of the list stored in _items }; 8
9
List Class with Static Array – Problems (Review) Stuck with "one size fits all" Could be wasting space Could run out of space Better to have instantiation of specific list specify what the capacity should be Thus we consider creating a List class with dynamically- allocated array 9
10
Dynamic-Allocation for List Class Changes required in data members Eliminate const declaration for CAPACITY Add variable data member to store capacity specified by client program Change array data member to a pointer Constructor requires considerable change Little or no changes required for empty() display() erase() insert() 10
11
List Class with Dynamic Array template class List { public: List(); bool isEmpty() const; bool insert(const T&, const int&); bool remove(const int&); void display(ostream&) const; private: T* _items; // array to store list elements int _size; // current size of the list stored in _items int_capacity; //current amount of allocated memory }; 11
12
New Functions Needed (Review) “Rule of 3” if need one, probably need all 3 of these functions Destructor When class object goes out of scope the pointer to the dynamically allocated memory is reclaimed automatically The dynamically allocated memory is not The destructor reclaims dynamically allocated memory Copy Constructor When argument passed as value parameter When function returns a local object When temporary storage of object needed When object initialized by another in a declaration Assignment Operator Default assignment operator makes shallow copy Can cause memory leak, dynamically-allocated memory has nothing pointing to it Function would essentially create a new array and copy the element values of the existing array, into the new array Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 12
13
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 13 http://www.screeninsults.com/ghostbusters.php http://www.american-buddha.com/GHOST.253.htm
14
Linked List Linked list NODE contains Data part – stores an element of the list Next part – stores link/pointer to next element (when no next element, null value) 14
15
Linked Lists - Advantages Access any item as long as external link to first item maintained Insert new item without shifting Delete existing item without shifting Can expand/contract as necessary 15
16
Linked Lists - Disadvantages Overhead of links: used only internally, pure overhead If dynamic, must provide destructor copy constructor Assignment operator No longer have direct access to each element of the list Many sorting algorithms need direct access Binary search needs direct access Access of n th item now less efficient must go through first element, and then second, and then third, etc. 16
17
Linked Lists - Disadvantages List-processing algorithms that require fast access to each element cannot be done as efficiently with linked lists. Consider adding an element at the end of the list 17 ArrayLinked List a[size++] = value; Get a new node; set data part = value next part = null_value If list is empty Set first to point to new node. Else Traverse list to find last node Set next part of last node to point to new node. This is the inefficient part
18
Data Members for Linked-List Implementation A linked list will be characterized by**: A pointer to the first node in the list. Each node contains a pointer to the next node in the list The last node contains a null pointer As a variation first may be a structure also contain a count of the elements in the list 18
19
Array-Based Implementation of Linked Lists Given a list with names Implementation would look like this 19
20
Linked Lists with Head Nodes Dual algorithms can be reduced to one Create a "dummy" head node Serves as predecessor holding actual first element Thus even an empty list has a head node 20
21
Circular Linked Lists Set the link in last node to point to first node Each node now has both predecessor and successor Insertions, deletions now easier Special consideration required for insertion to empty list, deletion from single item list 21
22
Doubly-Linked Lists Bidirectional lists Nodes have data part, forward and backward link Facilitates both forward and backward traversal Requires pointers to both first and last nodes 22
23
Comparing List With Other Containers Note : list does not support direct access does not have the subscript operator [ ] 23 PropertyArray vector deque list Direct/random access ( [] ) Excellent Excellent Good NA Sequential access Excellent Excellent Good Excellent Insert/delete at front Poor Poor Excellent Excellent Insert/delete in middle Poor Poor Poor Excellent Insert/delete at end Excellent Excellent Excellent Excellent Overheadlowestlowlow/mediumhigh
24
The STL list Class Template A sequential container Optimized for insertion and erasure at arbitrary points in the sequence. Implemented as a circular doubly-linked list with head node. 24
25
The STL list Memory Management When a node is allocated 1. If there is a node on the free list, allocate it. This is maintained as a linked stack 2. If the free list is empty: a) Call the heap manager to allocate a block of memory (a "buffer", typically 4K) b) Carve it up into pieces of size required for a node of a list 25
26
Multiply-Ordered Lists Ordered linked list Nodes arranged so data items are in ascending/descending order Straightforward when based on one data field However, sometimes necessary to maintain links with a different ordering Possible solution Separate ordered linked lists – but wastes space Better approach Single list Multiple links 26
27
Sparse Matrices Note the resulting representation of the matrix 27 A =
28
Generalized Lists Examples so far have had atomic elements The nodes are not themselves lists Generalized List: a list where the elements themselves are lists Consider a linked list of strings The strings themselves can be linked lists of characters 28 This is an example of a generalized list
29
Introduction to Stacks A stack is a last-in-first-out (LIFO) data structure Adding an item Referred to as pushing it onto the stack Removing an item Referred to as popping it from the stack 29
30
A Stack Definition: An ordered collection of data items Can be accessed at only one end (the top) Operations: construct a stack (usually empty) check if it is empty Push: add an element to the top Top: retrieve the top element Pop:remove the top element 30
31
Selecting Storage Structure A better approach is to let position 0 be the bottom of the stack Thus our design will include An array to hold the stack elements An integer to indicate the top of the stack 31
32
Dynamic Array to Store Stack Elements Same issues regarding static arrays for stacks as for lists Can run out of space if stack set too small Can waste space if stack set too large As before, we demonstrate a dynamic array implementation to solve the problems Need destructor, copy constructor and assignment operator 32
33
Further Considerations What if dynamic array initially allocated for stack is too small? Could terminate Better to replace with larger array Creating a larger array Allocate larger array Use loop to copy elements into new array Delete old array Point _items variable at this new array 33
34
Linked Stacks Another alternative to allowing stacks to grow as needed Linked list stack needs only one data member Pointer myTop Nodes allocated (but not part of stack class) 34
35
Application of Stacks Consider events when a function begins execution Activation record (or stack frame) is created Stores the current environment for that function. Contents: 35
36
Use of Run-time Stack When a function is called … Copy of activation record pushed onto run-time stack Arguments copied into parameter spaces Control transferred to starting address of body of function 36
37
Use of Run-time Stack When function terminates Run-time stack popped Removes activation record of terminated function exposes activation record of previously executing function Activation record used to restore environment of interrupted function Interrupted function resumes execution 37
38
Evaluation of Postfix Note the changing status of the stack 38
39
39 The Queue As an ADT A queue is a sequence of data elements In the sequence Items can be removed only at the front Items can be added only at the other end, the back LIFO Basic operations Construct a queue Check if empty Enqueue (add element to back) Front (retrieve value of element from front) Dequeue (remove element from front)
40
40 Designing and Building a Queue Class Array-Based Consider an array in which to store a queue Note additional variables needed myFront, myBack Picture a queue object like this
41
41 Linked Queues Constructor initializes myFront, myBack Front return myFront->data Dequeue Delete first node (watch for empty queue) Enqueue Insert node at end of list
42
42 Circular Linked List Possible to treat the linked list as circular Last node points back to first node Alternatively keep pointer to last node rather than first node
43
43 Application of Queues: Buffers and Scheduling Also times when insertions, deletions must be made from both ends Consider a scrolling window on the screen This requires a double ended queue Called a deque (pronounced "deck") Could also be considered a double ended stack (or "dack") A doubly-linked list is a natural implementation of the deque ADT
44
Queue as a Linked List If we use a singly-linked list: The front element is stored at the head of the list The rear element is stored at the tail of the list
45
Queue as a Linked List Enqueue() Adding an element to the queue is insertion after the last node newptr = new Node(value) if (empty()) { front = newPtr; rear = newPtr; } else { rear->next = newPtr; rear = rear->next; } What about front()? isEmpty()?
46
Queue as a Linked List Dequeue Simply delete the element that front is pointing to. ptr = front; front = front->next; delete ptr; We must also check if the queue is now empty. If it is, then we must make the talk point to null as well if (front == 0) { talk = 0; } How to get size()?
47
Stack as a dynamic array Need: An array to hold the stack elements An integer to indicate the top of the stack (or an integer that maintains the size)
48
Class Definition template class Stack { public: Stack(); Stack(const int&); Stack(const Stack&); ~Stack(); bool empty() const; bool push(const T&); bool pop(); T top(); const Stack& operator=(const Stack& rhs); void display(ostream&) const; private: T* _items; int _size; int _capacity;};
49
Push() The push operation is the insert operation for a stack. We must check if the array is full before attempting to add an element to the stack. template bool Stack ::push(const T& value) { if (_size>=_capacity) { return false; } _items[_size] = value; ++_size; }
50
Pop() This function removes the top item from the stack. We must be careful that we do not decrement size if it is already an empty stack. template bool Stack ::pop() { if (_size<=0) { return false; } --_size; return true; } What about the top() function?
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.