Two-Dimensional Arrays Introduction to Linked Lists COMP53 Sept
Many games and simulations have a two- dimensional “domain” Such domains can be represented by a two- dimensional array or matrix 2D arrays use two indices [i][j] to represent [row][column] or [x][y] position Two Dimensional Arrays
□ Arrays in Java are 1D □ 2D arrays are defined as an “array of arrays” □ int[][]M = new int[5][4]; □ This creates an array of ints with 5 rows and 4 columns □ What’s the value of M[3][1]? □ What’s M[3].length?
Tic-Tac-Toe How can we use a 2D array to represent a TTT board? X 1 O X 1 O
Nesting Loops Over a 2D Array double[][] array = new double[3][4]; int row, col, k; k = 1; for (row=0; row<array.length; row++) for (col=0; col<array[0].length; col++) array[row][col] = k++; Since columns were the inner loop, we walked across before down
Nesting Loops Over a 2D Array double[][] array = new double[3][4]; int row, col, k; k = 1; for (col=0 ; col<array[0].length; col++) for (row=0; row<array.length; row++) array[row][col] = k++; Since rows were the inner loop, we walked down before across
Printing a 2D Array public static void printArray2D(double[][] _a) { int r, c; for (r=0; r<_a.length; r++) { for (c=0; c<_a[0].length; c++) { System.out.print(_a[r][c]+"\t"); } System.out.println(); } columns needs to be inner loop, since an entire row is printed on one line.
Simulating a 2D Array We can use 1D arrays for 2D data, with a bit of cleaver indexing. i = row*sizeOfRow + col [0,0] 0 [0,1] 1 [0,2] 2 [1,0] 3 [1,1] 4 [1,2] 5 [2,0] 6 [2,1] 7 [2,2] 8 row 0row 1row 2
Singly Linked List A singly linked list is a concrete data structure consisting of a sequence of nodes Each node stores – an element – a link to the next node next elem node ABCD
Node Class for SLLs public class Node{ private Object element; private Node next; public Node() { this(null, null); } public Node(Object e, Node n) { element=e; next=n; } public Object getElement() { return element; } public Node getNext() { return next; } public void setElement(Object newElem) { element = newElem; } public void setNext(Node newNext) { next = newNext; } }
Singly Linked List: head and tail The list object must keep track of the first node in the list – usually called the head The list object may also keep track of the last node in the list – usually called the tail ABCD headtail
Inserting at the Head 1.Allocate a new node 2.Insert new element 3.Have new node point to old head 4.Update head to point to new node
Removing at the Head 1.Update head to point to next node in the list 2.Allow garbage collector to reclaim the former first node
Inserting at the Tail 1. Allocate a new node 2. Insert new element 3. Have new node point to null 4. Have old last node point to new node 5. Update tail to point to new node
Removing at the Tail Removing at the tail of a singly linked list is not efficient! We have to look through the list to find the new tail.