Week 3 - Friday CS221
Last time What did we talk about last time? Array implementation of a list
Questions?
Assignment 2
Project 1 Bitmap Manipulator
Assignment 1 issues Most people messed up the add() method that takes an index Most people didn't throw exceptions at quite the right times or didn’t throw them at all There was a lot of inconsistent formatting I don't specify what your formatting should be too closely, but it should be consistent Check out the coding standards for the course: http://users.etown.edu/w/wittmanb/cs221/standards/
Specific Assignment 1 don'ts Don't create a new Node unless you have to: Never look at the next thing unless you have to: Node temp = new Node(); //wastes memory temp = head; public boolean contains(int element) { Node temp = head; while(temp.next != null){ //two different bugs if( temp.value.equals(element) ) return true; temp = temp.next; } return false;
Specific Assignment 1 don'ts Don't use == to compare two String objects! public boolean contains(int element) { Node temp = head; while(temp != null){ // following might not work! if( temp.value == element) ) return true; temp = temp.next; } return false;
String comparison What happens when you use == for String comparison? String a = "Goats"; String b = "Goats"; String c = new String("Boats"); String d = new String("Boats"); if( a == b ) // prints System.out.println("a == b"); if( c == d ) // doesn't print System.out.println("c == d");
Specific Assignment 1 do's Use other methods to simplify code: Except when it doesn't make sense Using get() in addAll() is inefficient Keep it simple: Test, test, test! public boolean contains(int element) { return indexOf(element) != -1; } public boolean isEmpty() { return size == 0; }
Stacks Impromptu Student Lecture
Stacks
Stack A stack is a simple (but useful) ADT that has three basic operations: Push Put an item on the top of the stack Pop Remove an item from the top of the stack Top Return the item currently on the top of the stack (sometimes called peek)
Keeping track of things When are stacks used? Implicitly, in recursion (or in any function calls) Explicitly, when turning recursive solutions into iterative solutions When parsing programming languages When converting infix to postfix
Implementations
Array implementations Advantages: Pop is Θ(1) Top is Θ(1) Disadvantages Push is Θ(n) in the very worst case, but not in the amortized case
Array implementation public class ArrayStack { private int[] data; private int size; public ArrayStack() {} public void push(int value) {} public int pop() {} public int peek() {} //instead of top public int size() {} }
Array Constructor
Array Push
Array Pop
Array Peek
Array Size
Upcoming
Next time… Queue implementation with dynamic array Linked lists
Reminders Keep reading section 1.3 Finish Assignment 2 Due tonight by 11:59pm Keep working on Project 1 Due next Friday, September 22 by 11:59pm