Вы находитесь на странице: 1из 18

Final Exam - Study Guide

Simple Compilation of All Study Guides


FVCproductions - December 2014

Basic Definitions & Phrases


abstract data type
taken straight from the textbook
a data structure is the underlying programming construct used to implement a
collection
abstractions
ignores or hides certain details at certain times, e.g. collection is abstraction where
details of implementation are hidden
abstract in abstract data type
means that there are many different ways of implementing data type
algorithm
step by step instructions on how to execute a program or set of instructions
data structure
memory structure with associated representation mapping, e.g. a collection is a type
of data structure that acts as an object that gathers & organizes other objects
a data type is specified by describing both
its set of values & operations used for implementation
implementing an abstract data type proceeds in 2 stages
declaring necessary variables of data types
writing methods & procedures to implement operations of data for given data types

Arrays
overview
fixed size
more efficient b/c it uses less memory
easier to manage

collection
linear
can add/remove at any position
Defining an array (character type) of a size 3 called array
char [] array = new char[10]

Ask user to enter 10 characters and assign each of the character into array
for (int i = 0; i < array.length; i++)
array[i] = keyboard.next().charAt(0);

Use the data in array to reverse a list called reverse so that the first element in the list
called array is the last element in reverse
for (int i = 0; i < array.length; i++)
reverse[reverse.length i] = array[i];

Write the first use way to use for-loop to print out all elements in the list called reverse
for (int i = 0; i < reverse.length; i++)
System.out.print(reverse[i] + );

Write the second use way to use for-loop to print out all elements in the list called reverse
for (char value : reverse)
System.out.print(value + );

Define a 3 by 4 floating point values array, called scores


double [][] scores = new double [3][4];

Assign the value for each cell in the array called scores to
columnIndex * 20 / rowIndex

for (int row = 0; row < scores.length; row++)


for (int col = 0; col < scores[row].length; col++)
scores[row][col] = col * 20 / (double) row;

Print all the values in the array called scores

for (int row = 0; row < scores.length; row++) {


for (int col = 0; col < scores[row].length; col++)
System.out.print (scores[row][col] + \t);
System.out.println();
}

Write a findMax method which finds the maximum value in the data stored in scores
static double findMax(double [][] scores) {
double max = scores[0][0];
for (int row = 0; row < scores.length; row++)
for (int col = 0; col < scores[row].length; col++)
if (scores[row][col] > max)
max = myScores[row][col];
return max;
}

Comparing Stacks and Queues


Stacks and queues are similar data structures.
Theyre different only by how an item is removed first
Both can be implemented as arrays or linked lists.

Properties of Stacks
overview
example of a collection SDT
since stacks are lists, any list implementation will do
Last In, First Out data structure
can be implemented as an array
can only access the top
harder to manage b/c only top can be accessed
defintion
data structure of ordered items such that items can be inserted and removed only at 1
end (called the top )
diagram

conceptual implementation
First In, First Out (FIFO)
add to rear and remove from front
operations
push - adds item to stack
pop - deletes item from stack
peek - looks at top item in stack
size - returns # of elements in stack by examining top
isEmpty - tests for emptiness in stack by examining top

Stack Code & Algorithms


isEmpty
int top = -1; //or 0
public boolean isEmpty () {
return (top == -1);
}

isFull

public boolean isFull() {


return (top == size-1);
}

add to stack
public void add (int element) {
if (isFull() == true)
System.out.println("Stack full, cannot add element.");
else
stack[++top] = element;
}

1. check if stack is not full


2. set top position of array to element being added to stack
3. increment values of top and count (if partially filled array)
delete from stack
public int delete () {
if (isEmpty() == true)
System.out.println("Stack empty, cannot delete element.");
else
return stack[top--];
}

1. check if stack is not empty


2. decrement top
3. set return value to top position of array
print in order
public void printOrder() {
while(!isEmpty()) {
int value = remove();
System.out.print(value + " ");
}
}

find an element in stack

public boolean find(int element) {


System.out.print("Please enter element to find: ");
element = keyboard.nextInt();
for (int i = 0; i < size; i++) {
if (stack[i] == element)
return true;
}
return false;
}

Properties of Queues
overview
example of a collection SDT
operations: enqueue (add), dequeue (delete)
defintion
data structure of ordered items that can be inserted only at end (rear) and removed at
other end (front)
diagram

conceptual implementation
First In, First Out (FIFO)
add to rear and remove from front
operations
enqueue - adds item to queue

dequeue - removes item from queue


first - looks at top item in stack - so front
size - returns # of elements in queue by examining top
isEmpty - tests for emptiness by examining top

Queue Algorithms
shift queues
enqueue operation
1. save value at first index to item you want to enqueue
2. increment size
3. if array fills up, all n elements have to be copied to a new, larger array
dequeue operation
1. save value at first index
2. shift all elements left
3. decrement size
circular queues
advance queue indexes front (to delete an item) and back (to insert an item) by
moving them both clockwise around array

How To Choose Stacks Over Queues Or Vice-Versa


implementing a stack as an array is easy, but implementing a queue as an array is more
difficult because you have to dequeue from front and enqueue at end
if you want to be able to add or remove values from any position, arrays are the way to go
because any value can be accessed through indexes
main limitations of arrays is that they cannot be extended or shrunk so you want to use an
array when you know your max upper limit
if youre not sure how many values there will be in your data structure, then its better to not
use an array and stick with a linked list (ergo, queues)
because arrays always have a fixed size

Real Examples in Tech Where Stacks Queues Are Used


examples of stacks
CD storage case
cafeteria trays
batteries in a flashlight
cars in a single car garage

Towers of Hanoi
examples of queues
waiting line for a roller coaster
hamburger processing line at Mickey Ds
undo button
vehicles on a toll bridge
luggage checking machine
phone answering system for Apples customer support

Linked Lists vs Arrays


Arrays
can access any element directly via indexing
all elements grouped together
sitting in 1 block of memory
size is fixed
Linked Lists
each element sits in own block of memory (called node)
nodes can only be accessed in sequential order
appears limited
size varies - nodes allocated on need basis
list elements can be easily inserted/removed without reallocation and at any point in
the list
no random access to data
no efficient form of indexing
Key Differences
underlying layout of data in memory
how individual elements are accessed

Linked Lists Properties


overview
a sequence of elements arranged 1 after another with each element connected to
next by a link
one of the simplest and most common data structures
can be used to implement other abstract data types
defintion
data structure of group of nodes that represent a sequence
diagram

above is a linked list with nodes that contain 2 fields - an integer value and a link to next to
the next node; last node linked to terminator symbol to signify end of list/null link
conceptual implementation
each node has data and reference (link) to next node in sequence
allows for insertion of removal of elements from any position in sequence
operations for singly linked list
insertion
deletion
traversal - going through entire sequence until reaching last node

advantages
dynamic data structure that allocates needed memory
easy implementation for insertion and deletion operations
other data structures can be easily executed with linked lists
reduce access time and can expand without more memory being used
disadvantages
usually wastes memory with pointers which requires extra storage space
nodes must be read sequentially
nodes stored in an in-contiguous manner, so more difficult to access individual nodes
very difficult to reverse traverse

Linked Lists Algorithms


constructor for an integer node in a linked list
public Int_Node (int initialData, Int_node initialLink) {
data = initialData; //integer value
link = initialLink; //reference to next node in list
}

define empty linked list


Int_Node head = null;

pseudocode
1. representing empty list by storing null in head reference
keeping track of front node by using an Int_Node reference variable called
head

add new node to empty list


head = new Int_Node(data, null);

pseudocode
1. create new node for head
2. place data in new nodes data field
3. make head refer to null which is initial head value
4. connect new node to head
add node to front of list
head = new Int_Node(newData, head);

pseudocode
1. create new node
2. place data ( newData ) in new nodes data field
3. connect new node to front of list
4. make original head refer to new head of linked list

Diagram showing how a node is inserted after an existing node Inserting node before
existing node cannot be done directly - instead you have to keep track of the previous
node and insert a node after that
adding anywhere but front
previous.link = new Int_Node(newData, previous.link);
while (prev.link != null) {
prev = head;
prev = prev.link;
}

pseudocode
1. set a reference named prev (for previous) to refer to node which is just before
new nodes position
removing node at head

head = head.link;

pseudocode
1. directing head to node right next to it ( head.link ) so that original head is
removed
removing node anywhere

Removing node after given node - to find and remove a particular node, you still have to
keep track of the previous element
traverse through list
Int_Node pointer = head;
while (pointer != null) {
pointer = pointer.link;
}

pseudocode
1. initializing pointer to reference head
2. while loop that keeps going through entire list until pointer (or head ) is null
null implying that its reached the last node because the last node will

always have a null link since theres nothing next to the last node so no
link so null link
3.

pointer referenced to next node or pointer.link

print list through traversal

Int_Node pointer = head;


while (pointer != null) {
System.out.print(pointer.data + " ");
pointer = pointer.link;
}

pseudocode
same as traversal algorithm but just printing out data of pointer as you go along
the node sequence with pointer.data

Binary Trees
trees
a structure with unique starting point - root - where each node can have multiple
children nodes, and a unique path exists from the root node to every other node
root
top node of a tree structure, a node with no parent
binary tree
structure where each item is called a node and where each node can have a max of
two children, left and right child node

diagram:
leaf
node with no children
descendant

child of a node
ancestor
parent of a node
binary search tree
binary tree where value in any node is greater than or equal to value in its left child
and any of descendants (nodes in left subtree) and less than value in its right child
and any of its descendants (nodes in right subtree)

diagram:
full binary tree
binary tree where all of leaves are on same level and every nonleaf node has 2
children
complete binary tree
binary tree that is full or full through next-to-last level, with leaves on last level as far
as possible

balanced tree
left and right subtrees of any node are the same height

preorder
node/root, left, right
inorder
left, node/root, right
postorder
left, right, node/root

FUN TIP I
a fast way to remember this is through the following, starting by writing r in the far left
then fill it out with L or R, representing left or right, as follows:
r L R - preorder
L r R - inorder
L R r - postorder
FUN TIP II
in-order traversal is probably easiest to see, because it sorts the values from
smallest to largest (literally)

How to Delete A Binary Search Tree


no successor
1. if node is leaf, simply removed
2. but if root is leaf, pointer to tree assigned null value
one successor
1. parent node connected to sucessor node
2. deleted node disposed of
two successors
1. find logical predecessor (node in left subtree with largest value)
2. logical predecessor replaces deleted node

Recursion
recursive method is a method that calls itself
in many cases, recursive algorithms are less efficient than iterative algorithms
recursive solutions repetitively
allocate memory for parameters and local variables
store address of where control returns after method terminates
basically works like this:
a base case is established
if matched, method solves it and returns
if base case cannot be solved
method reduces it to smaller problem (recursive case) and calls itself to solve
smaller problem

examples of recursion in real life


quick sort, merge sort, flowers,Towers of Hanoi, Fibonacci sequence, factorials

towers of hanoi fun pic:

example 1 provided - emptyVase


void emptyVase(int flowersInVase) {
if (flowersInVase > 0) {
//takes one flower
emptyVase(flowersInVase-1);
} else {
// vase is empty, nothing to do
}
}

example 2 provided - Recursion2


public class Recursion2 {
public void countItDown(int counter) {
if (counter == 0)
return;
else {
System.out.println("Count: " + counter);
counter--;
countItDown(counter);
System.out.println("" + counter);
return;
}
}
public static void main (String[] args) {
Recursion2 myRecursor = new Recursion2();
myRecursor.countItDown(5);
}
}

example 3 provided - count

count(n)
if (n > 0)
print n
count (n-1)
else
print done
count: n --> n = 3
count: (n-1) --> n = 2
count: (n-1) --> n = 1
count: (n-1) --> n = 0

example 4 - from textbook Foundations of Java


public class Recursive {
public static void message(int n) { //displays message n times
if (n > 0) {
System.out.println("This is a recursive method.");
message(n-1);
}
}
}

example 5 - from textbook Foundations of Java


public static int fib(int n) { // returns nth number in Fibonacci sequence
if (n == 0)
return 0;
else if (n == 1)
return 1;
else
return fib(n - 1) + fib(n - 2);
}

example 6 - from textbook Foundations of Java


public static int factorial(int n) { // returns factorial of non-negative argument
if (n == 0)
return 1;
else
return n * factorial(n-1);
}

example 7 - from textbook Foundations of Java

public static int gcd(int x, int y) { // returns greater common denominator of two ar
if (x % y == 0)
return y;
else
return gcd(y, x % y);
}

Tips or Tricks?
Contact me @fvcproductions

Вам также может понравиться