CS2 - PowerPoint PPT Presentation

1 / 82
About This Presentation
Title:

CS2

Description:

Ex-Girlfriend. You're going to finally remove. that picture of your old Ex-girlfriend, Brittany, who never. really cared for you. ( Long story. ... – PowerPoint PPT presentation

Number of Views:148
Avg rating:3.0/5.0
Slides: 83
Provided by: ccGa
Category:
Tags: cs2 | girlfriend

less

Transcript and Presenter's Notes

Title: CS2


1
CS2
  • Module 27
  • Category CS Concepts
  • Topic Linked Lists
  • Objectives
  • Linked Lists
  • Stacks
  • Queues

2
CS 2
  • Introduction to
  • Object Oriented Programming
  • Module 27
  • CS Concepts
  • Linked Lists - Stacks - Queue

3
Evolving Data Structures Linked Lists
4
!
Imagine you just broke up with your girlfriend...
Here, certain gender assumptions are made. Bear
with us.
5
Linked Lists Review
Its time to clean off your desk. Time to
replace your photographs
She was no good for you anyway.
6
So, you put the old photograph in a box (just in
case she calls).
... next to the boxes holding pictures of the
other celebrities you once dated.
7
And then it hits you
cs2 can help organize the wreckage that is your
social life.
8
How So?
Instead of using boxes, it might be better to use
a linked list structure.
Mistakes I Have Made
9
How So?
Instead of using boxes, it might be better to use
a linked list structure.
Mistakes I Have Made
10
How So?
Instead of using boxes, it might be better to use
a linked list structure.
Mistakes I Have Made
11
How So?
Instead of using boxes, it might be better to use
a linked list structure.
Mistakes I Have Made
12
How So?
Instead of using boxes, it might be better to use
a linked list structure.
Mistakes I Have Made
13
How So?
Instead of using boxes, it might be better to use
a linked list structure.
Mistakes I Have Made
14
Immediately you start coding
15
public class Picture private String
strName private Picture next public
Picture (String strNome) setName(strName) setN
ext(null) public void setNext(Picture
next) this.next next public
Picture getNext() return next
public String getName() return strName
public void setName(String strName) this.strNa
me strName // Picture
Looks good. Are we done coding this class?
No. Wheres the debug main?
You might think DEBUG MAIN? Who needs a debug
main?
You do!
16
OK, OK
public static void main(String args)
Picture pTest new Picture ("Britany
Spears") String strTemp pTest.getName() Syst
em.out.println ("I was dumped by " strTemp)
// main
Alright, so you decide to code a test main for
this dinky little class. What a bother.
17
Eh? What Happened?
When you test the class, you find, to your
complete surprise, that theres a bug.
18
public class Picture private String
strName private Picture next public
Picture (String strNome) setName(strName) setN
ext(null) public void setNext(Picture
next) this.next next public
Picture getNext() return next
public String getName() return strName
public void setName(String strName) this.strNa
me strName // Picture
But my code compiled. You explain to your TA.
Mere compilation is insignificant compared to
the power of debugging.
19
Prepare the Autograder to fire on the debug main
20
public class Picture private String
strName private Picture next public
Picture (String strNome) setName(strName) setN
ext(null) public void setNext(Picture
next) this.next next public
Picture getNext() return next
public String getName() return strName
public void setName(String strName) this.strNa
me strName public static void
main(String args) Picture pTest new
Picture ("Britany Spears") String strTemp
pTest.getName() System.out.println ("I was
dumped by " strTemp) // main // Picture
Wheres the bug?
Good. So a few of you alert folks spotted
it. Now. How long would it take you to find
this bug if you had 12 classes and 2,500 lines of
code to sort through?
at 3 a.m...?
21
You protest But I tried to just code the
classes--
22
What Else is Missing?
Lesson learned ALWAYS use a debug main. But
what else have we forgotten?
Anyone, anyone? Bueller? Anyone?
public String toString() public boolean
equals(Object o)
23
public String toString() return "Picture
of " getName() public boolean
equals (Object oTemp) boolean bEqual
false if (oTemp instanceof Picture)
Picture pic (Picture) oTemp if
(pic.getName().equals(getName())) bEqual
true return bEqual public
static void main(String args) Picture pTest
new Picture ("Britany Spears") String strTemp
pTest.getName() System.out.println ("I was
dumped by " strTemp) Picture pSecond new
Picture ("Britany Spears") System.out.println
("Picture 1 " pTest) System.out.println
("Picture 2 " pSecond) System.out.println
("Equals? " pTest.equals(pSecond)) Integer
iTemp new Integer (42) System.out.println
("Is Britany equal to an Integer? "
pTest.equals(iTemp))
After fixing our bug, we continue
New methods? TEST THEM
24
Invest 5 minutes doing trivial tests as you make
the class. . . . . . or spend hours searching
through reams of code later.
25
Are we done with this class?
NO. Our debug main tests all the methods, but
does not test all the conditions. We failed to
compare two different Picture objects.
26
Doh!
So, we add more to our main, so that each
expected condition for each method gets tested
27
public boolean equals (Object oTemp) boolean
bEqual false if (oTemp instanceof Picture)
Picture pic (Picture) oTemp if
(pic.getName().equals(getName())) bEqual
true return bEqual public
static void main(String args) Picture pTest
new Picture ("Britany Spears") String strTemp
pTest.getName() System.out.println ("I was
dumped by " strTemp) Picture pSecond new
Picture ("Britany Spears") System.out.println
("Picture 1 " pTest) System.out.println
("Picture 2 " pSecond) System.out.println
("Equals? " pTest.equals(pSecond)) Integer
iTemp new Integer (42) System.out.println
("Is Britany equal to an Integer? "
pTest.equals(iTemp)) Picture pThird new
Picture ("Chewbacca") System.out.println ("Is
Britany equal to Chewbacca? "
pThird.equals(pTest))
Why did our equals() method fail? Trace the code
28
Were Not Kidding
Your debug main MUST a) Test all the methods
in the class, no matter how trivial, b) Test
all the conditions that the methods are expected
to handle, no matter how trivial.
29
No one knows how to test yourcode as well as you
do.
  • Not Yoda.
  • Not Ferris Bueller
  • Not Ben Stein
  • Not Brittany Spears
  • Not Sisqo
  • Not Carson Daly
  • Not Hannibal Lecter
  • Not Sponge Bob Square Pants
  • No, not even Al Gore who invented your code.

No one but you.
30
((W(h)e)re)?
Where Were We?
  • So weve just finished creating a class to
    represent our old photographs.
  • It differs from a mere record class from cs1, in
    that weve also included mutators for each
    instance variable. That is, the class also has
    methods that provides access to the variables,
    and lets us change things.
  • We have fields for data
  • A String reference
  • A next Picture reference
  • We have accessors/modifiers (aka getters
    setters)
  • We override the inherited Object methods
  • toString() - which otherwise prints memory
    addresses
  • equals() - which otherwise uses
  • We wrote a debug main, to avoid trouble.

31
public class PictureCollection private
Picture head
We start with a PictureCollection class. We need
an instance variable to act as the head node.
We make it private because (a) this concerns
our personal picture collection, and (b)
we dont want others poking around in
our collection, unless we let them.
32
public class PictureCollection private
Picture head public Picture
getHead() return head public void
setHead(Picture head) this.head head

Now that we have an instance variable,
our instincts take over. We immediately know
that we must have accessors/modifiers for this
variable.
33
public class PictureCollection private
Picture head public Picture
getHead() return head public void
setHead(Picture head) this.head head
public void insert (Picture
newPicture) if (head null)
setHead(newPicture) else insert
(newPicture, getHead())
We then code a method to insert a new Picture
reference.
34
public class PictureCollection private
Picture head public Picture
getHead() return head public void
setHead(Picture head) this.head head
public void insert (Picture
newPicture) if (head null)
setHead(newPicture) else insert
(newPicture, getHead()) public void
insert(Picture newPicture, Picture current) if
(current.getNext() null)
current.setNext(newPicture) else insert
(newPicture, current.getNext())
We then create a method to recurse to JUST
BEFORE the end of the linked list.
35
public class PictureCollection // . .
. public void insert(Picture newPicture,
Picture current) if (current.getNext()null)
current.setNext(newPicture) else insert
(newPicture, current.getNext())
Lets trace the logic here...
Data String1
Data String2
Data String3
head
Lets presume we had this structure in memory .
. .
36
public class PictureCollection // . .
. public void insert(Picture newPicture,
Picture current) if (current.getNext()null)
current.setNext(newPicture) else insert
(newPicture, current.getNext())
Lets trace the logic here...
Data String1
Data String2
Data String3
head
New Item
37
public class PictureCollection // . .
. public void insert(Picture newPicture,
Picture current) if (current.getNext()
null) current.setNext(newPicture) else
insert (newPicture, current.getNext())
Lets trace the logic here...
We evaluate the first conditional
Data String1
Data String2
Data String3
head
New Item
38
public class PictureCollection // . .
. public void insert(Picture newPicture,
Picture current) if (current.getNext()
null) current.setNext(newPicture) else
insert (newPicture, current.getNext())
Lets trace the logic here...
We evaluate the first conditional
Data String1
Data String2
Data String3
head
New Item
Its not null, so we skip down to the else clause
. . .
39
public class PictureCollection // . .
. public void insert(Picture newPicture,
Picture current) if (current.getNext()
null) current.setNext(newPicture) else
insert (newPicture, current.getNext())
Lets trace the logic here...
Data String1
Data String2
Data String3
head
New Item
This promotes our current to the next Picture,
and we recurse. . .
40
public class PictureCollection // . .
. public void insert(Picture newPicture,
Picture current) if (current.getNext()
null) current.setNext(newPicture) else
insert (newPicture, current.getNext())
Lets trace the logic here...
Data String1
Data String2
Data String3
head
New Item
Once again, we see if the current has null next
reference . . .
41
public class PictureCollection // . .
. public void insert(Picture newPicture,
Picture current) if (current.getNext()null)
current.setNext(newPicture) else insert
(newPicture, current.getNext())
Lets trace the logic here...
Data String1
Data String2
Data String3
head
New Item
Again, we skip down to the else clause, which
promotes our current
42
public class PictureCollection // . .
. public void insert(Picture newPicture,
Picture current) if (current.getNext()null)
current.setNext(newPicture) else insert
(newPicture, current.getNext())
Lets trace the logic here...
Data String1
Data String2
Data String3
head
New Item
Finally, we check the conditional, and the next
is null.
43
public class PictureCollection // . .
. public void insert(Picture newPicture,
Picture current) if (current.getNext()null)
current.setNext(newPicture) else insert
(newPicture, current.getNext())
Lets trace the logic here...
Data String1
Data String2
Data String3
head
New Item
So, we set the next reference to be our
newPicture reference.
44
public class PictureCollection // . .
. public void insert(Picture newPicture,
Picture current) if (current.getNext()null)
current.setNext(newPicture) else insert
(newPicture, current.getNext())
Lets trace the logic here...
Data String1
Data String2
Data String3
New Item
head
Recursion unwinds, and we leave method, having
updated our list.
45
public class PictureCollection private
Picture head public Picture
getHead() return head public void
setHead(Picture head) this.head head
public void insert (Picture
newPicture) if (head null)
setHead(newPicture) else insert
(newPicture, getHead()) public void
insert(Picture newPicture, Picture current) if
(current.getNext()null) current.setNext(new
Picture) else insert (newPicture,
current.getNext())
So, this appears to work on paper. Whats
missing?
46
Debug Main
So you add a debug main.
public static void main(String args)
PictureCollection pcTemp new PictureCollection()
for (int i 0 i pcTemp.insert (new Picture ("Test Picture "
i))
The trouble is, how do you print out whats in
the list?
We need to code a method to help with this...
47
Overloaded toString()
public String toString() String strRet
"Picture List\n" return toString(getHead(),
strRet) // toString private String
toString(Picture current, String strRet) if
(current ! null) strRet
current.toString() "\n" return
toString(current.getNext(), strRet) else
return strRet // toString
Note We made the overloaded method private,
since users will most likely only need to call
just the toString() method.
48
We then have our test main call this toString()
method and print out whats in the test
PictureCollection
49
Code Review
We just coded a set of classes to handle the
storage of Picture objects. We modeled the data
structure on a linked list, but made some design
mistakes.
Our Picture references can only hold Strings. We
cant use them to hold other object types, unless
we convert them to a String. (This is not
desirable!)
Our PictureCollection class works ONLY with
Picture types. If we later want to make a
similar collection, say, of baseball cards, we
then have to write an entirely new class, perhaps
borrowing some code.
Yet borrowing code is done perfectly through an
inheritance mechanism. But our design does not
make it logical to have (for example) baseball
items extending pictures of old girl friends.
50
Code Review (contd)
We just coded a set of classes to handle the
storage of Picture objects. We modeled the data
structure on a linked list, but made some design
mistakes.
Further, we do not have a mechanism for comparing
one Picture reference to another. What if we
wanted to sort the items by date, name, or some
other criteria? We have no method that allows
comparisons.
In short, we need to consider two factors in our
design
51
public class Node private Object data
private Node next public Node (Object
data) setData(data) setNext(null)
public void setNext (Node
next) this.next next public Node
getNext() return next public Object
getData() return data public void
setData (Object data) this.data
data // Node
public class Picture private String
strName private Picture next public
Picture (String strName) setName(strName) setN
ext(null) public void setNext
(Picture next) this.next next public
Picture getNext() return next
public String getName() return strName
public void setName (String
strName) this.strName strName //
Picture
52
public class Node private Object data
private Node next public Node (Object
data) setData(data) setNext(null)
public void setNext (Node
next) this.next next public Node
getNext() return next public Object
getData() return data public void
setData (Object data) this.data
data // Node
public class Picture private String
strName private Picture next public
Picture (String strName) setName(strName) setN
ext(null) public void setNext
(Picture next) this.next next public
Picture getNext() return next
public String getName() return strName
public void setName (String
strName) this.strName strName //
Picture
Now a linked list of Nodes, not merely Pictures
53
public class Node private Object data
private Node next public Node (Object
data) setData(data) setNext(null)
public void setNext (Node
next) this.next next public Node
getNext() return next public Object
getData() return data public void
setData (Object data) this.data
data // Node
public class Picture private String
strName private Picture next public
Picture (String strName) setName(strName) setN
ext(null) public void setNext
(Picture next) this.next next public
Picture getNext() return next
public String getName() return strName
public void setName (String
strName) this.strName strName //
Picture
Now holds Object references, and not merely
Strings
54
public class PictureCollection private
Picture head public Picture
getHead() return head public void
setHead(Picture head) this.head head
public void insert(Picture newPicture)
if (head null) setHead(newPicture)
else insert (newPicture, getHead())
public void insert (Picture newPicture,
Picture current) if (current.getNext()null)
current.setNext(newPicture) else
insert (newPicture,
current.getNext())
public class LinkedList private Node
head public Node getHead() return head
public void setHead(Node head) this.head
head public void insert (Node
newNode) if (head null)
setHead(newNode) else insert (newNode,
getHead()) public void insert (Node
newNode, Node current) if (current.getNext()
null) current.setNext(newNode)
else insert (newNode,
current.getNext())
Same Idea
55
Comparing Objects
Note that we have not gained the ability to store
generic data types. But we still lack the
ability to sort these data types.
Lets return to our attempt to model the Node
data type.
56
public class Node implements Comparable
private Comparable data private Node next
public Node (Comparable data) setData(data) se
tNext(null) public void setNext(Node
next) this.next next public Node
getNext() return next public Comparable
getData() return data public void
setData (Comparable data) this.data data
public int compareTo(Object oTemp) Node
nTemp (Node) oTemp Comparable cTemp
oTemp.getData() return getData().compareTo(c
Temp) // Node
public class Node private Object data
private Node next public Node (Object
data) setData(data) setNext(null)
public void setNext (Node
next) this.next next public Node
getNext() return next public Object
getData() return data public void
setData (Object data) this.data
data // Node
57
public class Node implements Comparable
private Comparable data private Node next
public Node (Comparable data) setData(data) se
tNext(null) public void setNext
(Node next) this.next next public
Node getNext()return next public Comparable
getData() return data public
void setData (Comparable
data) this.data data public int
compareTo (Object oTemp) Node
nTemp (Node) oTemp Comparable cTemp
oTemp.getData() return getData()
.compareTo(cTemp) // Node
public class Node private Object data
private Node next public Node (Object
data) setData(data) setNext(null)
public void setNext (Node
next) this.next next public Node
getNext() return next public Object
getData() return data public void
setData (Object data) this.data
data // Node
We switch again from Object types
to Comparable types.
58
The Comparable Interface
Lets say a few more words about the Comparable
interface
As you know, Java does not support multiple
inheritance. Instead, we can use interfaces to
force the implementing class to have certain
methods. Theres an interface called Comparable
that requires a compareTo method. This method
returns an int telling you the difference between
two instances.
FYI Tangent Note that the dynamic binding of
toString() would skip over Comparable, which does
not have a toString() method.
Node n new Node()
n
59
The Comparable Interface
Lets say a few more words about the Comparable
interface
Each interface indeed does define a reference new
type! So you can polymorph an object by using an
interface reference type. Even though the
interface is just a stub (cant use it to create
objects) - its still a reference type.
Quiz alert
Comparable c new Node()
c
60
Up Close
calling compareTo from the datas class
public int compareTo (Object oTemp) Node
nTemp (Node) oTemp Comparable cTemp
nTemp.getData() return getData().compareTo(cT
emp)
When writing a compareTo( ) method, always write
it so that it returns a negative number when the
calling object is smaller than the parameter
object! (0 when equal, and positive
otherwise) When in doubt, look at the API read
the comments it has within the Comparable
interface!!! Returns a negative integer, zero,
or a positive integer as this object (the calling
one) is less than, equal to, or greater than the
specified object (the parameter).
61
Where This is Headed
NodeType
Object
Comparable
Node
Note that this design differs from our
existing generic node structure. A third
generation (not shown) is needed to improve the
Node
TreeNode
LinkNode
We can use interfaces to abstract out behaviors,
and create generic structures that work for
Trees, Linked Lists, Stacks, etc.
62
compareTo Summary
You must make a policy decision about what it
means to compare objects. Use your decision
and implement the Comparable interface. Sometimes
, as in the case of a Node class, we code the
compareTo method by merely asking the stored data
which is larger. (Thereby passing the
buck!) Sometimes, we might not do this. Watch
the order in which you compare objects. TEST
YOUR CODE.
63
QUESTIONS?
64
Whats the big deal with linked lists?
  • Linked lists are used extensively in Computer
    Science
  • They are very often used to implement stacks and
    queues.
  • Why?
  • They are also used to keep things in order
  • when the number of items is small or
  • performance is not too important

65
Stacks
  • Stacks are LIFO data structures. LIFO Last In
    First Out
  • Stacks are useful in many applications
  • Recursion
  • Handling interruptions
  • Keeping track of the "last one" (e.g. nested ifs)
  • Stacks can be implemented using
  • Arrays (Advantages/Disadvantages?)
  • Linked Lists (Advantages/Disadvantages?)
  • Typical stack operations
  • push - Add an element to the stack
  • pop - Remove an element from the stack
  • isEmpty()
  • isFull() more rare
  • peek() - rare

66
Stacks
  • Smart quick and easy
  • Push Add to front of List
  • Pop Remove from front of List
  • Dumb counterproductive
  • Push Add to end of list (loop or recursion)
  • Pop Remove last element of List (loop or
    recursion)

67
Implementation
public class Node private Object data
private Node next public Node(Object
data) setData(data) setNext(null)
public void setNext(Node next) this.next
next public Node getNext() return
next public Object getData() return
data public void setData(Object data)
this.data data // Node
68
Stack
  • class Stack
  • private Node head
  • public Stack()
  • head null
  • // Constructor
  • public boolean isEmpty()
  • return (head null)
  • // isEmpty

69
Stack
  • // class Stack (continued)
  • public void push(Object o)
  • if (isEmpty())
  • head new Node(o)
  • else
  • Node temp new Node(o)
  • temp.setNext(head)
  • head temp
  • // push

70
Stack
  • // class Stack (continued)
  • public Object pop()
  • // lets assume that by contract we are to throw
    an
  • // exception when attempting to pop an empty
    stack
  • if (isEmpty())
  • throw new java.util.EmptyStackException()
  • Object retval head.getData()
  • head head.getNext()
  • return retval
  • // pop
  • Note EmptyStackException is a RuntimeException

71
Stack
  • // class Stack (continued)
  • public String toString()
  • Node current head
  • String retval "Stack\n"
  • while(current ! null)
  • retval "" current.getData() "\n"
  • current current.getNext()
  • return retval
  • // toString()

72
Stack
  • // class Stack (continued)
  • public static void main(String args)
  • Stack s new Stack()
  • System.out.println(s.isEmpty())
  • System.out.println("Empty stack test " s)
  • s.push("Bottom")
  • s.push("Middle")
  • s.push("Top")
  • System.out.println(s.isEmpty()
  • while(!s.isEmpty())
  • System.out.println("Popping " s.pop())
  • System.out.println("Remains " s)
  • // while
  • // main
  • // Stack

73
Output
  • true
  • Empty stack test Stack
  • false
  • Popping Top
  • Remains Stack
  • Middle
  • Bottom
  • Popping Middle
  • Remains Stack
  • Bottom
  • Popping Bottom
  • Remains Stack

74
Questions?
75
Chew on this...
  • Write a program which will
  • accept lines of text and
  • check that parentheses are balanced
  • Examples
  • () () () Okay
  • ((())) Okay
  • (()()()) Okay
  • )))((( Bad
  • ())(() Bad

One must always seek balance
76
KEY Use a stack...
  • Algorithm
  • examine all characters, processing one character
    at a time
  • If ( push onto stack
  • If ) pop stack
  • Check stack at the end
  • Stack empty at end success!
  • Stack non-empty - failure to be balanced
  • Error conditions Popping from empty stack
  • Stack not empty at end of line

77
  • public boolean scan(String line)
  • boolean retval true
  • Stack myStack new Stack()
  • for (int i 0 i
  • char c line.charAt(i)
  • if (c '(' )
  • myStack.push( "(" )
  • else if (c ')' )
  • try
  • Object o myStack.pop()
  • catch (java.util.EmptyStackException e)
  • return false //parens not balanced
  • // for
  • if (!myStack.isEmpty())
  • retval false

Notice we handle the exception and simply realize
that to us it means the parentheses were not
balanced -- A normal situation, so just
return the correct, false, value.
78
Questions?
79
Queues
  • Queues are FIFO data structures. FIFO First In
    First Out
  • Queues are useful in many applications
  • Simulations
  • Operating systems
  • Schedulers
  • Queues can be implemented using
  • Arrays (Advantages/Disadvantages?) (How???)
  • Linked Lists (Advantages/Disadvantages?)
  • Typical stack operations
  • Enqueue - Add an element to the tail of the Queue
  • Dequeue - Remove an element from head of the
    Queue
  • isEmpty() - Doh?
  • isFull() - Duh?
  • Peek() or Front() - Necessary (Why?)

80
More Truth in CS
  • In class it is common to implement a queue
    yourself
  • In reality, Java comes with a variety of useful
    classes predefining Stacks, Queues, etc.
  • Remember the API is your friend!
  • Example java.util.LinkedList
  • Methods include
  • boolean add(Object o) // Add to the end of the
    list
  • void addFirst(Object o) // Adds to beginning of
    list
  • void clear() // Removes all items from list
  • Object getFirst() // Returns first element of
    list
  • Object getLast() // Returns last element of list
  • Object removeFirst() // Remove and return first
    elem.
  • Object removeLast() // Remove and return last
    element

81
Questions?
82
(No Transcript)
Write a Comment
User Comments (0)
About PowerShow.com