chapter 9: linked lists learn about linked lists. learn about doubly linked lists. get used to...

44
Chapter 9: Linked Lists • Learn about linked lists. • Learn about doubly linked lists. • Get used to thinking about more than one possible implementation of a data structure. • Think about the advantages and disadvantages of different implementations. 06/09/22

Upload: cameron-nash

Post on 16-Jan-2016

272 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Chapter 9: Linked Lists Learn about linked lists. Learn about doubly linked lists. Get used to thinking about more than one possible implementation of

Chapter 9: Linked Lists

• Learn about linked lists.• Learn about doubly linked lists.• Get used to thinking about more than one

possible implementation of a data structure.• Think about the advantages and

disadvantages of different implementations.

04/21/23

Page 2: Chapter 9: Linked Lists Learn about linked lists. Learn about doubly linked lists. Get used to thinking about more than one possible implementation of

Reading

• Bailey Chapter 9

04/21/23 CS2007, Dr M. Collinson

Page 3: Chapter 9: Linked Lists Learn about linked lists. Learn about doubly linked lists. Get used to thinking about more than one possible implementation of

Linked lists: the idea

• A linked list is a set of items where each item is part of a node that may also contain a single link to another node.

• Allow one to insert, remove and rearrange lists very efficiently.

04/21/23 CS2007, Dr M. Collinson

Page 4: Chapter 9: Linked Lists Learn about linked lists. Learn about doubly linked lists. Get used to thinking about more than one possible implementation of

Linked lists: data structure

• A linked list consists of a sequence of nodes connected by links, plus a header.

• Each node (except the last) has a next node, and each node (except the first) has a predecessor.

• Each node contains a single element (object or value), plus links to its next.

ant bat cat

header null linknode element link

04/21/23 CS2007, Dr M. Collinson

Page 5: Chapter 9: Linked Lists Learn about linked lists. Learn about doubly linked lists. Get used to thinking about more than one possible implementation of

More about linked lists

• The length of a linked list is the number of nodes.• An empty linked list has no nodes.• In a linked list:

– We can manipulate the individual elements.– We can manipulate the links,

• Thus we can change the structure of the linked list! • This is not possible in an array.

04/21/23 CS2007, Dr M. Collinson

Page 6: Chapter 9: Linked Lists Learn about linked lists. Learn about doubly linked lists. Get used to thinking about more than one possible implementation of

Points to Note

• Last element may use a special link called the null link.

• Different implementations of linked lists.• Different forms:

– Circular lists: `last’ item linked to `first’.– Cyclic: `last’ item linked to one of its predecessors. – Acyclic: not cyclic. 14506

– Nodes sometimes drawn: ant

04/21/23 CS2007, Dr M. Collinson

Page 7: Chapter 9: Linked Lists Learn about linked lists. Learn about doubly linked lists. Get used to thinking about more than one possible implementation of

04/21/23

Page 8: Chapter 9: Linked Lists Learn about linked lists. Learn about doubly linked lists. Get used to thinking about more than one possible implementation of

Linked Lists vs. Arrays

• Size of linked list can be variable! – Arrays have fixed size.

• Re-arrangement of items in a linked list is (usually) faster.

• Access to elements is slower in a LL. 04/21/23 CS2007, Dr M. Collinson

Page 9: Chapter 9: Linked Lists Learn about linked lists. Learn about doubly linked lists. Get used to thinking about more than one possible implementation of

References

• Many languages use references or pointers to implement linked lists.

• This is the case in Java, where references are pointers to objects. See Malik, chapter 3.

• A node consists of a variable for the data it carries (which may be done via a reference), and a variable which is a reference to its next.

04/21/23 CS2007, Dr M. Collinson

Page 10: Chapter 9: Linked Lists Learn about linked lists. Learn about doubly linked lists. Get used to thinking about more than one possible implementation of

Pitfalls with Pointers

• You should be aware that programming with references is very powerful, but can be tricky.

• Aliasing: `If two variables contain references to the same object, the state of the object can be modified using one variable’s reference to the object, and then the altered state can be observed through the reference in the other variable.’ (Gosling, Joy, Steele, The Java Language Specification).

04/21/23 CS2007, Dr M. Collinson

Page 11: Chapter 9: Linked Lists Learn about linked lists. Learn about doubly linked lists. Get used to thinking about more than one possible implementation of

Null

• The last node of a linked list is a reference, but it is the null reference that refers to nothing!

• If some operation tries to use the object that the null ref. points to then an exception is raised (in Java NullPointerException).

• Not always easy to ensure all of these are caught.• `I call it my billion-dollar mistake. It was the invention

of the null reference in 1965. … This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years.’ (Prof. Sir C.A.R. Hoare)

04/21/23 CS2007, Dr M. Collinson

Page 12: Chapter 9: Linked Lists Learn about linked lists. Learn about doubly linked lists. Get used to thinking about more than one possible implementation of

A Java Class of Nodes• Nodes for a linked list (of strings).

class SLLNode {String element; // data fieldSLLNode next; // next field

// Constructor

SLLNode (String elem, SLLNode nextNode) {this.element = elem;this.next = nextNode;

}}

04/21/23 CS2007, Dr M. Collinson

Page 13: Chapter 9: Linked Lists Learn about linked lists. Learn about doubly linked lists. Get used to thinking about more than one possible implementation of

Java class: linked list with header

• Implementing linked list of SLLNodes:

class StrLinkedList { SLLNode first; // Header refers to first node

// Constructor for empty list StrLinkedList () { this.first = null; }

}

04/21/23 CS2007, Dr M. Collinson

Page 14: Chapter 9: Linked Lists Learn about linked lists. Learn about doubly linked lists. Get used to thinking about more than one possible implementation of

Example of list creation

list = new StrLinkedList();

SLLNode catNode = new SLLNode(“cat”,null);

SLLNode batNode = new SLLNode(“bat”,catNode);

SLLNode antNode = new SLLNode(“ant”,batNode);

list.first = antNode;

ant bat cat

04/21/23 CS2007, Dr M. Collinson

Page 15: Chapter 9: Linked Lists Learn about linked lists. Learn about doubly linked lists. Get used to thinking about more than one possible implementation of

What happens?

• System.out.println(list.first.data);

• System.out.println(list.first.next.data);

• System.out.println(list.first.next.next.data);

• System.out.println( list.first.next.next.next.data );

04/21/23 CS2007, Dr M. Collinson

Page 16: Chapter 9: Linked Lists Learn about linked lists. Learn about doubly linked lists. Get used to thinking about more than one possible implementation of

Example of list traversal• Add method (to class StrLinkedList) to traverse list. Prints

all elements in first-to-last order. • Note clever Boolean condition on while loop. Commonly

used trick. Such methods may not always terminate -- for example on lists with cycles.

void printFirstToLast () {SLLNode current = this.first;while (current != null) {

System.out.println(current.data);current = current.next;}

return; }

04/21/23 CS2007, Dr M. Collinson

Page 17: Chapter 9: Linked Lists Learn about linked lists. Learn about doubly linked lists. Get used to thinking about more than one possible implementation of

Array lists: retrieve/get

• get(index): return the data at the specified index.

• Speed does not depend on the size of the array or the index. Therefore get is O(1).

04/21/23 CS2007, Dr M. Collinson

Page 18: Chapter 9: Linked Lists Learn about linked lists. Learn about doubly linked lists. Get used to thinking about more than one possible implementation of

Linked lists: Retrieval

• Get item at given position index.

String get(int index) {

SLLNode current = this.first;

for (int count = 0; count++; count < index)

current = current.next

return current.data;

}

04/21/23 CS2007, Dr M. Collinson

Page 19: Chapter 9: Linked Lists Learn about linked lists. Learn about doubly linked lists. Get used to thinking about more than one possible implementation of

Time complexity

• Time complexity: takes index+1 steps. – O(1) to get first element– O(N) to get last element– O(N) to get randomly chosen element.

• Same complexity class (= roughly the same speed) as ArrayList to get first element. Slower to get other elements

04/21/23 CS2007, Dr M. Collinson

Page 20: Chapter 9: Linked Lists Learn about linked lists. Learn about doubly linked lists. Get used to thinking about more than one possible implementation of

Array lists: remove (deletion)

• remove(index): remove the element at the index. Shuffle everything to the right of the index (but not the index itself) back one position. Decrement size (N).

• Best case: last element (1 assignment). • Worst case: first element (N+1 assignments).• In general: 1 + N – index assignments. • Average case: O(N).

04/21/23 CS2007, Dr M. Collinson

Page 21: Chapter 9: Linked Lists Learn about linked lists. Learn about doubly linked lists. Get used to thinking about more than one possible implementation of

Linked lists: deletion of node. • Idea: Re-wire the picture of linked list, cutting-out X, the

node at given position index. • That is, find predecessor of X in the list; call this pred. Then

change next of pred to be next of X. (To remove first node, change ref. to first field in header class).

void remove(int index) {if (index == 0) first = first.next;else { SLLNode pred = first; for (int count = 0; count < index-1; count++)

pred = pred.next; // for-loop ends here

pred.next = pred.next.next; } }

04/21/23 CS2007, Dr M. Collinson

Page 22: Chapter 9: Linked Lists Learn about linked lists. Learn about doubly linked lists. Get used to thinking about more than one possible implementation of

How remove works

• start pred at first node• advance pred index-1 times to get to node before

deletion • assign pred.next = pred.next.next

– to bypass the node to delete (44)

– any node with no reference to it is garbage collected04/21/23 CS2007, Dr M. Collinson

Page 23: Chapter 9: Linked Lists Learn about linked lists. Learn about doubly linked lists. Get used to thinking about more than one possible implementation of

Time Complexity: Linked List Removal

• Same speed as retrieval (get)– O(N) on average, O(1) to remove first

element– Most of the time is used to find the

predecessor.

• Same average speed as ArrayList– Faster to remove first element.

04/21/23 CS2007, Dr M. Collinson

Page 24: Chapter 9: Linked Lists Learn about linked lists. Learn about doubly linked lists. Get used to thinking about more than one possible implementation of

Arrays lists: Add

• Add(index, element): add an element to a list at a given index. Add one to the length (size) of the array(N), shuffle everything from the index onward one position to the right.– Best case (index = last element): 2 assignments.– Worst case (first element): N + 2 assignments. – In general, 2+ (N-index) assignments. – Average O(N).

04/21/23 CS2007, Dr M. Collinson

Page 25: Chapter 9: Linked Lists Learn about linked lists. Learn about doubly linked lists. Get used to thinking about more than one possible implementation of

Adding to a Linked List

• Adding at beginning: O(1)– special case in Add method

• Adding at end: O(N)– general case in Add method– uses a pointer variable to traverse list

04/21/23

Page 26: Chapter 9: Linked Lists Learn about linked lists. Learn about doubly linked lists. Get used to thinking about more than one possible implementation of

Adding to Beginning of a List• Adding 11 at index = 0 (the beginning):

– BEFORE

– AFTER:

04/21/23 CS2007, Dr M. Collinson

Page 27: Chapter 9: Linked Lists Learn about linked lists. Learn about doubly linked lists. Get used to thinking about more than one possible implementation of

Pseudocode for Adding to Beginning

• if (index == 0) // add to beginning of list– Create newNode as a new SLLNode with data– Assign newNode.next = first– Assign first = newNode

04/21/23

Page 28: Chapter 9: Linked Lists Learn about linked lists. Learn about doubly linked lists. Get used to thinking about more than one possible implementation of

Adding to Middle/End of List

• Adding 55 at index = 2– Before:

– After

04/21/23

Page 29: Chapter 9: Linked Lists Learn about linked lists. Learn about doubly linked lists. Get used to thinking about more than one possible implementation of

Psuedocode for Adding to Middle/End• if (index == 0) // add to beginning of list• ... // already shown • ...• else

– assign pred to first node– advance pred through list index-1 times

• so it now points to node before insertion point

– Create newNode as a new SLLNode with data– Assign newNode.next = pred.next– Assign pred.next = newNode

04/21/23

Page 30: Chapter 9: Linked Lists Learn about linked lists. Learn about doubly linked lists. Get used to thinking about more than one possible implementation of

Java code for Insertion/Add• Idea: re-wire picture so that predecessor of node N at given index

points to the new node, and new node points to N. Very similar to remove.

• Same speed as get(..) for LL: O(N) on average, O(1) to add first element.

void add(int index, String s) {if (index == 0)

first = new SLLNode(s, first); // Add to beginning

else { // Add to middle or end SLLNode pred = first; for (int count = 0; count < index-1; count++) // advance pred to node prior

pred = pred.next; SLLNode newNode = new SLLNode(s, pred.next); // create, link to rest of listpred.next = newNode; } } // link prior to newNode

04/21/23 CS2007, Dr M. Collinson

Page 31: Chapter 9: Linked Lists Learn about linked lists. Learn about doubly linked lists. Get used to thinking about more than one possible implementation of

List implementation: comparison

Array Single LL

Get(index) O(1) O(N)

Get(0) O(1) O(1)

Get(last) O(1) O(N)

Insert/remove O(N) O(N)

Ins/rem first O(N) O(1)

Ins/rem last O(1) O(N)

Page 32: Chapter 9: Linked Lists Learn about linked lists. Learn about doubly linked lists. Get used to thinking about more than one possible implementation of

Doubly-linked lists

• A doubly-linked list (DLL) consists of a sequence of nodes, connected by links in both directions.

• Each DLL node contains a single element, plus links to the node’s next and predecessor (or null link(s)).

• The DLL header contains links to the DLL’s first and last nodes (or null links if the DLL is empty).

pig dog ratcat

dog

04/21/23 CS2007, Dr M. Collinson

Page 33: Chapter 9: Linked Lists Learn about linked lists. Learn about doubly linked lists. Get used to thinking about more than one possible implementation of

Doubly-linked List

• Advantages– Fast access to beginning and end of list– Can traverse forwards or backwards

• See Malik for details on algorithms

04/21/23 CS2007, Dr M. Collinson

Page 34: Chapter 9: Linked Lists Learn about linked lists. Learn about doubly linked lists. Get used to thinking about more than one possible implementation of

A Java Class for DLL Nodes

• Java class implementing DLL nodes:

class DLLNode {String data;DLLNode predecessor, next;

// Constructor DLLNode(String elem, DLLNode pred, DLLNode succ) { this.data = elem; this.next = succ; this.predecessor = pred; }}

04/21/23 CS2007, Dr M. Collinson

Page 35: Chapter 9: Linked Lists Learn about linked lists. Learn about doubly linked lists. Get used to thinking about more than one possible implementation of

A Java Class for Doubly-linked Listsclass DLL {

DLLNode first, last;

// Constructor for an empty DLL. DLL () { this.first = null; this.last = null; }}

04/21/23 CS2007, Dr M. Collinson

Page 36: Chapter 9: Linked Lists Learn about linked lists. Learn about doubly linked lists. Get used to thinking about more than one possible implementation of

Example DLL construction

// set-up doubly-linked list

list = new DLL(); DLLNode catNode = new DLLNode("cat",null,null); DLLNode batNode = new DLLNode("bat",null,catNode); DLLNode antNode = new DLLNode("ant",null,batNode); catNode.predecessor = batNode; batNode.predecessor = antNode; list.first = antNode; list.last = catNode;

04/21/23 CS2007, Dr M. Collinson

Page 37: Chapter 9: Linked Lists Learn about linked lists. Learn about doubly linked lists. Get used to thinking about more than one possible implementation of

Speed of list implementation

Array Single LL Double LL

Get(index) O(1) O(N) O(N)

Get(0) O(1) O(1) O(1)

Get(last) O(1) O(N) O(1)

Insert/remove O(N) O(N) O(N)

Ins/rem first O(N) O(1) O(1)

Ins/rem last O(1) O(N) O(1)

Page 38: Chapter 9: Linked Lists Learn about linked lists. Learn about doubly linked lists. Get used to thinking about more than one possible implementation of

Which to use?

• Which implementation should we use?• Depends on how we are going to use the list

– Frequency of get, add, remove.– Usually at beginning or end of list, or can be

anywhere?

04/21/23 CS2007, Dr M. Collinson

Page 39: Chapter 9: Linked Lists Learn about linked lists. Learn about doubly linked lists. Get used to thinking about more than one possible implementation of

Efficiency of Stack implementations

Array Single LL Double LL

Get(last) O(1) O(N) O(1)

Ins/rem last O(1) O(N) O(1)

•Array or DLL better than SLL. •Array marginally faster than DLL.

Page 40: Chapter 9: Linked Lists Learn about linked lists. Learn about doubly linked lists. Get used to thinking about more than one possible implementation of

Efficiency: Queue/Dequeue

Array Single LL Double LL

Get(0) O(1) O(1) O(1)

Get(last) O(1) O(N) O(1)

Ins/rem first O(N) O(1) O(1)

Ins/rem last O(1) O(N) O(1)

» DLL better for Dequeue» Note: there is a clever array-implementation which

is fast: ArrayDeque in Java.

Page 41: Chapter 9: Linked Lists Learn about linked lists. Learn about doubly linked lists. Get used to thinking about more than one possible implementation of

(Space) Memory Efficiency

• Linked lists need a bit of extra space for the links.

• Array lists waste space if array bigger than list.

• Not a huge difference

04/21/23 CS2007, Dr M. Collinson

Page 42: Chapter 9: Linked Lists Learn about linked lists. Learn about doubly linked lists. Get used to thinking about more than one possible implementation of

Implementation Time

• Easy to do using Java Collections Framework:– java.util.LinkedList.

• If implementing directly:– Linked lists generally very easy, just add a “next”

field to the objects that hold data.– Array lists more complex, have to deal with

copying to bigger array.– Linked list widely used in languages without

collection classes (core C, Pascal).

04/21/23 CS2007, Dr M. Collinson

Page 43: Chapter 9: Linked Lists Learn about linked lists. Learn about doubly linked lists. Get used to thinking about more than one possible implementation of

Summary

• Linked lists are an alternative way of implementing lists to array lists

• In most cases ArrayList (ArrayDeque) faster– Although LinkedList better in a few cases

• Linked list easier to implement directly.

04/21/23 CS2007, Dr M. Collinson

Page 44: Chapter 9: Linked Lists Learn about linked lists. Learn about doubly linked lists. Get used to thinking about more than one possible implementation of

Java LinkedList

• List Interface:– http://download.oracle.com/javase/1.4.2/docs/ap

i/java/util/List.html

• LinkedList class– http://download.oracle.com/javase/1.4.2/docs/ap

i/java/util/LinkedList.html

04/21/23 CS2007, Dr M. Collinson