Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes."— Presentation transcript:

1 COMP 103 Linked Lists

2 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes TODAY  A second look at Linked Node  Implementing a LinkedList class

3 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?

4 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 Program ______________ My Program ______________ LinkedList Class ArrayList Class add remove add remove

5 5 Types of Lists: ArrayLists, LinkedLists > Collection > Collection > List > List > AbstractList > AbstractList > ArrayList > ArrayList > AbstractSequentialList > AbstractSequentialList > LinkedList > LinkedList underlying data structure: ARRAY underlying data structure: LINKED NODES

6 6 Making a LinkedList class class LinkedList { private LinkedNode head = null; public void printList( ) { for (LinkedNode rest = head; rest != null; rest = rest.next() ) System.out.printf("%s, ", rest.get()); } public void printList( ) { printList(head); } private void printList(LinkedNode list) { if (list == null) return; … // As before } Underlying data structure Iterative version Recursive version

7 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 C

8 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 (item, head); } else { int pos = 0; LinkedNode rest = head; // rest is the pos’th node while ( pos < n-1 ) { // stop at node before the n'th pos++; rest = rest.next(); } rest.setNext(new LinkedNode (item, rest.next())); } } WQRET head

9 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

10 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.

11 COMP 103 Linked Stack and Linked Queue

12 12 RECAP-TODAY RECAP  Linked data structures: Linked Node  LinkedList class TODAY  Linked Stack  Linked Queue  Other linked collections

13 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)

14 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

15 15 Implementing LinkedStack  Implementing a stack using LinkedNode as underlying data structure (instead of array) public class LinkedStack extends AbstractCollection { private LinkedNode 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

16 16 More LinkedStack methods public 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 data does 3 jobs...

17 17 Iterator (for any list)  Iterating down a stack. for (String str: myStack) System.out.println(str) J H M C X P data myStack node iterator

18 18 Iterator public Iterator iterator() { return new LinkedNodeIterator(data); } private class LinkedNodeIterator implements Iterator { private LinkedNode node; // node containing next item public LinkedNodeIterator (LinkedNode 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(); }

19 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

20 20 A 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

21 21  Keep pointers to both ends!  poll() O(1)  offer(“A”) O(1) A Better Linked Queue H M J X P C Front Back A

22 22 Implementing LinkedQueue public class LinkedQueue implements AbstractQueue { private LinkedNode front = null; private LinkedNode back = null; public LinkedQueue() { } public int size() { … public boolean isEmpty() { … public E peek() { … public E poll() { … public void offer(E item) { … public Iterator iterator() { … M A Front Back

23 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

24 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

25 25 LinkedQueue public 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

26 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.

27 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?


Download ppt "COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes."

Similar presentations


Ads by Google