COMP 103 Linked Lists. 2 RECAP-TODAY RECAP Linked Structures: LinkedNode Iterating and printing...

27
COMP 103 Linked Lists

Transcript of COMP 103 Linked Lists. 2 RECAP-TODAY RECAP Linked Structures: LinkedNode Iterating and printing...

Page 1: COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes.

CO

MP 1

03

Linked Lists

Page 2: COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes.

2

RECAP-TODAYRECAP Linked Structures: LinkedNode

Iterating and printing Linked Nodes Inserting and removing Linked Nodes

TODAY A second look at Linked Node Implementing a LinkedList class

Page 3: COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes.

3

Using linked structures Three common patterns:

just step along and drop off the end (e.g. print all of a list)

look for a node and stop there (e.g. printLast).

look for a node and stop at one before that (e.g. insert, remove)

Must be a node before the one we want! Can only apply to non-empty lists. Need unused node at the front, or make special case for

the first node!

Where do we put these methods?

Page 4: COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes.

4

LinkedNode and LinkedList LinkedNode is a data structure (a way to represent and store

data) much like an Array is a data structure We can use LinkedNode to implement a LinkedList class, much

like we can use an Array to implement an ArrayList class Linked List class ‘wraps’ the LinkedNode data structure and has

methods to manipulate it (add, remove, size etc), much like the way ArrayList class ‘wraps’ the Array data structure and has methods to manipulate it (add, remove, size, etc)

A B A B

Data structure: Linked Node Data structure: Array

My Progra

m _____________________LinkedList Class ArrayList Class

add

removeaddremove

Page 5: COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes.

5

Types of Lists: ArrayLists, LinkedLists

<<interface>>Collection

<<interface>>List

<<abstract class>>

AbstractList

<<class>>

ArrayList

<<abstract class>>

AbstractSequentialList

<<class>>

LinkedList

underlying data structure: ARRAY

underlying data structure: LINKED NODES

Page 6: COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes.

6

Making a LinkedList classclass LinkedList <E> {

private LinkedNode<E> head = null;

public void printList( ) {

for (LinkedNode<E> rest = head; rest != null; rest = rest.next() )System.out.printf("%s, ", rest.get());

}public void printList( ) { printList(head); }

private void printList(LinkedNode<E> list) {if (list == null) return;

… // As before

}

}

Underlying data structure

Iterative version

Recursive version

Page 7: COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes.

7

Separate "header" object Separate object to represent the list as a whole

Two different classes: List type = object with a field with pointer to first node Node type = (underlying) data structure to hold the items

+ An empty list is an object that you can call methods on⇒ fits with the object oriented style of programming

- Half the linked list is not a List.⇒ can’t share list structure so easily

BA

head head

C

Page 8: COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes.

8

Inserting (iterative)/** Insert the value at position n in the list (counting from 0)

Assumes list is not empty, and 0 <= n < length */

public void insert (E item, int n) {if ( n == 0 ) {

head = new LinkedNode<E>(item, head);} else {

int pos = 0;LinkedNode<E> rest = head; // rest is the pos’th nodewhile ( pos < n-1 ) { // stop at node before the n'th

pos++;rest = rest.next();

}rest.setNext(new LinkedNode<E>(item, rest.next()));

}}

WQ RE T

head

Page 9: COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes.

9

Inserting (recursive)/** Insert the value at position n in the list (counting from 0)

Assumes list is not empty, and 0 <= n < length */

public void insert (E item, int n) {if ( n == 0 )

head = new LinkedNode<E>(item, head); else

insert(item, n, head.next( ));}

/** This is the recursive insert method – note it takes 3 arguments */

private void insert (E item, int n, LinkedNode<E>list) {if ( n == 1 )

list.setNext(new LinkedNode<E>(item, list.next( )); else

insert(item, n-1, list.next( ));}

eg. insert X at position 2 in mylist

Page 10: COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes.

10

Exercises Write both iterative and recursive methods to

do the following, for linked list and array lists. Remove a value from a list, allowing the value to

occur anywhere; leave the list unchanged if value is not in the list.

Remove a node from a given position in a list. Append one list onto the end of another. Reverse a list. Insert a list at a given position in another list. Count/return/remove all the elements that

satisfy a given property. Insert/delete elements in a sorted list. Merge two sorted lists.

Page 11: COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes.

CO

MP 1

03

Linked Stackand

Linked Queue

Page 12: COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes.

12

RECAP-TODAYRECAP Linked data structures: Linked Node LinkedList class

TODAY Linked Stack Linked Queue Other linked collections

Page 13: COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes.

13

A Linked Stack Implement a Stack using a linked list.

Which end is the top of the stack?

pop()

push(“A”)

Why is this a bad idea?

J

H

M

C

X

P

data

A

TOP

O(n)

Page 14: COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes.

14

A Linked Stack Make the top of the Stack be the head of the list.

pop()

push(“A”)

J

H

M

A

C

X

P

data

TOP

Page 15: COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes.

15

Implementing LinkedStack Implementing a stack using LinkedNode as

underlying data structure (instead of array)

public class LinkedStack <E> extends AbstractCollection<E> {

private LinkedNode<E> data = null;

public LinkedStack() {  } // constructor

public int size() { … }

public boolean empty() { … }

public E peek() { … } // Usually called top

public E pop() { … }

public void push(E item) { … }

public int search(Object o) { … }

// plus others inherited from AbstractCollection, such as toArray() and others...

}

data

Page 16: COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes.

16

More LinkedStack methodspublic boolean empty() {

return data == null;}

public E peek() { if (data == null) throw new EmptyStackException(); return data.get();}

public E pop() { if (data == null) throw new EmptyStackException(); E ans = data.get(); data = data.next(); return ans;}

public void push(E item) { if (item == null) throw new IllegalArgumentException(); data = new LinkedNode(item, data);}

M

H

datadata

does 3 jobs...

Page 17: COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes.

17

Iterator (for any list) Iterating down a stack.

for (String str: myStack)

System.out.println(str)

J

H

M

C

X

Pdata

myStack

node

iterator

Page 18: COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes.

18

Iteratorpublic Iterator <E> iterator() {

    return new LinkedNodeIterator(data);} private class LinkedNodeIterator <E> implements Iterator <E> {

private LinkedNode<E> node;     // node containing next item public LinkedNodeIterator (LinkedNode <E> node) {

this.node = node;}

public boolean hasNext () {return (node != null);

}

public E next () {if (node == null) throw new NoSuchElementException();E ans = node.get();node = node.next();return ans;

}

public void remove () {throw new UnsupportedOperationException();

}}

Page 19: COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes.

19

A Linked Queue #1 Put the front of the queue at the end of the list

offer(“A”) O(1)

poll() O(n)

J

M

C

X

P

H

back

A

Front

Page 20: COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes.

20A Linked Queue #2

Put the front of the Queue at the start of the list.

poll() O(1)

offer(“A”) O(n) is too Slow!!

J

H

M

C

X

P

Front

A

Back

Page 21: COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes.

21

Keep pointers to both ends!

poll() O(1)

offer(“A”) O(1)

A Better Linked Queue

H

M

JX

P

C

Front

Back

A

Back

Page 22: COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes.

22

Implementing LinkedQueuepublic class LinkedQueue <E> implements AbstractQueue <E> {

private LinkedNode<E> front = null;private LinkedNode<E> back = null;

public LinkedQueue() {  }

public int size() { …

public boolean isEmpty() { …

public E peek() { …

public E poll() { …

public void offer(E item) { …

public Iterator <E> iterator() { …

M

A

Front

Back

Page 23: COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes.

23

LinkedQueue

public boolean isEmpty() { return front == null;

}

public int size () {if (front == null)   return 0;else   return front.size();

}

public E peek() {if (front == null) return null;else return front.get();

}

M

A

Front

Back

Front

Back

Page 24: COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes.

24

LinkedQueue

public E poll() {

if (front == null) return null;

E ans = front.get();

front = front.next();

if (front == null) back = null;

return ans;}

M

A

Front

Back

A

Front

Back

Front

Back

three cases: 0 items, 1 item, >1 items

Page 25: COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes.

25

LinkedQueuepublic boolean offer(E item) {

if (item == null) return false;if (front == null) {    back = new LinkedNode(item, null);    front = back;}else {     back.setNext(new LinkedNode(item, null));    back= back.next();}return true;

}

M

A

Front

Back

A

Front

Back

Front

Back

three cases: >1 item, 1 item, 0 items

Page 26: COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes.

26

Linked Stacks and Queues Use a “header node”

Keep link to head node, and maybe last node of linked list

Important to choose the right end. Easy to add or remove from head of a linked list Easy to add to last node of linked list (if have pointer to tail

too) Hard to remove the last node of linked list (do you see why?)

Linked Stack and Queue: all main operations are O(1)

Can combine Stack and Queue giving Dequeue. addFirst, addLast, removeFirst (or pushLeft, pushRight,

popLeft) How can we make all operations fast? See the java “LinkedList” class.

Page 27: COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes.

27

Other linked collections Set

Can store sorted or unsorted What is the cost of add, remove, contains, size,

equals in each case? Bag

Same as set, but add a count to each node. Map

Same as set, but store value as well as key in each node

Or store pointed to a key-value pair What is the cost of get, put, remove?