Week 12 Tutorial
In this week’s tutorial, we’ll look at working with multiple linked lists, manipulating stacks and queues, some simple recursions, and implementing a simple Final Card-Down player.
Multiple Linked Lists
We’ve seen how to deal with one linked list… what about more?
-
How might I append one List to another?
-
How might I prepend one List to another?
-
How might I interleave, or “zip”, values from two lists?
That is, given two lists and , the result would be .
-
How might I insert values into the list in order?
That is, given the same two lists the result would be .
Stacks and Queues
In lectures, we’ve seen how ADTs allow us to define separate implementations that may radically differ in their approach, but which conform to the same interface.
We saw the Stack
ADT again:
a stack is a last-in-first-out data structure.
We also saw how to implement it
with linked lists; here’s Stack.h
:
Another simple data structure is a first-in-first-out data structure the queue. The operations on a queue are to enqueue and dequeue a value.
-
What might a
Queue
ADT interface look like? -
How might we implement one using a linked list to store values?
-
How might we implement one using a Stack?
Simple Recursion
Hofstadter’s Law: It always takes longer than you expect, even when you take into account Hofstadter’s Law. — Douglas Hofstadter, Gödel, Escher, Bach: An Eternal Golden Braid
In lectures, we’ve seen the basics of programming recursively: we define a function that has a base case, and a recursive case.
-
What is a base case? What does a base case define?
-
What is a recursive case?
-
Why do we need base cases?
A trivial example of a recursion is to calculate the triangle numbers. The sequence of triangle numbers goes:
Here’s its definition, mathematically.
-
What’s the base case of ?
-
What’s the recursive case of ?
-
How might we implement a function
int tri (int n)
?
We can transform some recursive functions into iterations, and some iterative functions into recursions.
We’ve already seen a recursion, and calculated it iteratively:
- How might we define
escapeSteps
recursively?
Playing The Final Card-Down
There are three parts to assignment 2: the first two – to test, and implement, the Game ADT – you’ve already seen and should be working hard on. The third part is to implement an artificial intelligence that plays the game.
We’ve provided a header file, player.h
,
which looks a lot like this:
-
What do we need to do to implement the simplest
player.c
?- You might want to look at the valid moves diagram
You need to work with your lab partner
to implement a player.c
;
in the lab today,
you should get started on that.
In the next competition rounds, we’ll run games with all the submitted players, so you should submit a compiling player.
Next Week…
… is our last week! Have a party!
(… and maybe think about the various things we’ve learned over the course of this semester!)