CS 2430 Day 35
Agenda Introduction to linked lists Bag as linked list Stack as linked list
Growing slowly Do you remember the grow() method? What is its big O complexity? O(N), where N is the number of elements in the Bag, Queue, etc. Therefore, add(), enqueue(), etc., had worst case big O of O(N)
Growing faster Can we make a growable Bag class with O(1) worst case add() method? Yes, we can! We cannot use an array We will use a “linked list”
Introduction to linked lists
Linked lists Arrays are random access, i.e., access to array element is O(1) Linked lists can have data scattered all over memory Therefore, linked lists are (mostly) sequential access
Nodes Each element of a linked list is a Node Nodes have “info” and “next” fields The “next” field points to the next node in the list
The Node class class Node { public Object info; public Node next;// Note the type! public Node(Object theInfo, Node theNext) { info = theInfo; next = theNext; } }
An empty list Node list; // points to null... ► ► Ølist
Insert x at the back list = new Node(x, null);... What is the big O? O(1) ► ► xlistØØ
Insert y at the back list.next = new Node(y, null);... ► ► listxØyØ
Insert z at the back list.next.next = new Node(z, null);... ► ► listxØyØz
Delete from the front list = list.next;... What is the big O? O(1) ► ► listxyzØ
Insert at front list = new Node(w, list);... What is the big O? O(1) ► ► list w yzØ
Print everything out Node p = list; while (p != null) { System.out.println(p.info); p = p.next; } ► ► ► ► ► ► list p xyzØ
Always draw pictures when working linked list problems
Any questions?
Go to THE THING:
Growable Bag as linked list public class Bag { private Node list; public Bag() {... } public boolean add(Object obj) {... } // insert at front public boolean isEmpty() {... } public int size() {... } public void reset() {... } public boolean contains(Object target) {... } public boolean remove(Object obj) {... } } We will do some of the methods
public class Bag { private Node list; public boolean add(Object obj) { list = new Node(obj, list); return true; } }
public class Bag { private Node list;... public boolean isEmpty() { return list == null; } public void reset() { list = null; } }
public class Bag { private Node list;... public int size() { int count = 0; Node p = list; while (p != null) { count++; p = p.next; } return count; } } What is the big O? O(N) I think we can do better than this!
public class Bag { private Node list; private int count = 0; public void reset() { count = 0; list = null; }... }
public class Bag { private Node list; private int count;... public boolean add(Object obj) { list = new Node(obj, list); count++; return true; } public int size() { return count; } } Now size(), add(), reset() and isEmpty() are all O(1)