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

Slides:



Advertisements
Similar presentations
Chapter 25 Lists, Stacks, Queues, and Priority Queues
Advertisements

Stacks, Queues, and Linked Lists
Chapter 24 Lists, Stacks, and Queues
Linked Lists Linear collections.
AITI Lecture 19 Linked List Adapted from MIT Course 1.00 Spring 2003 Lecture 26 and Tutorial Note 9 (Teachers: Please do not erase the above note)
Computer Science 112 Fundamentals of Programming II Queues and Priority Queues.
Chapter 6 The Collections API. Simple Container/ Iterator Simple Container Shape [] v = new Shape[10]; Simple Iterator For( int i=0 ; i< v.length ; i++)
Stacks, Queues, and Deques. 2 A stack is a last in, first out (LIFO) data structure Items are removed from a stack in the reverse order from the way they.
CHAPTER 4 Queues MIDTERM THURSDAY, OCTOBER 17 IN LAB.
Chapter 6 Linked Structures © 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
COMP 103 Linked Stack and Linked Queue.
CS 106 Introduction to Computer Science I 12 / 06 / 2006 Instructor: Michael Eckmann.
1 Chapter 24 Lists Stacks and Queues. 2 Objectives F To design list with interface and abstract class (§24.2). F To design and implement a dynamic list.
Unit 11 1 Unit 11: Data Structures H We explore some simple techniques for organizing and managing information H This unit focuses on: Abstract Data Types.
CS 106 Introduction to Computer Science I 12 / 11 / 2006 Instructor: Michael Eckmann.
TCSS 342, Winter 2005 Lecture Notes
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 26 Implementing Lists, Stacks,
CS 106 Introduction to Computer Science I 12 / 13 / 2006 Instructor: Michael Eckmann.
1 Lecture 26 Abstract Data Types – IV Overview  The List ADT  Implementing Stacks as Linked List  Linked List Implementation of Queues .  Preview:
Stacks, Queues, and Deques
1 Stack Data : a collection of homogeneous elements arranged in a sequence. Only the first element may be accessed Main Operations: Push : insert an element.
Stacks, Queues, and Deques. A stack is a last in, first out (LIFO) data structure –Items are removed from a stack in the reverse order from the way they.
Stacks, Queues, and Deques
CSE 373 Data Structures and Algorithms Lecture 2: Queues.
CM0551 Exam Prep. What are an algorithm’s time and space complexity? (2 marks) Answer: The growth rate of the algorithm’s time requirement and the computer.
COMP 103 Priority Queues, Partially Ordered Trees and Heaps.
Information and Computer Sciences University of Hawaii, Manoa
Some Other Collections: Bags, Sets, Queues and Maps COMP T2 Lecture 4 School of Engineering and Computer Science, Victoria University of Wellington.
CSE 12 – Basic Data Structures Cynthia Bailey Lee Some slides and figures adapted from Paul Kube’s CSE 12 CS2 in Java Peer Instruction Materials by Cynthia.
School of Engineering and Computer Science, Victoria University of Wellington COMP 103 Linked Structures.
1 Chapter 7 Stacks and Queues. 2 Stack ADT Recall that ADT is abstract data type, a set of data and a set of operations that act upon the data. In a stack,
Data Structures (part 2). Stacks An Everyday Example Your boss keeps bringing you important items to deal with and keeps saying: “Put that last ‘rush’
Data structures Abstract data types Java classes for Data structures and ADTs.
09-1 Queues and List-Based ADT Implementations Problem Set: PS3 due Wednesday, March 7 Wellesley College CS230 Lecture 09 Monday, February 26 Handout #18.
HIT2037- HIT6037 Software Development in Java 22 – Data Structures and Introduction.
Queue FIFO (First In First Out) Java Doc peek, element offer poll, add
COP INTERMEDIATE JAVA Data Structures. A data structure is a way of organizing a collection of data so that it can be manipulated effectively. A.
2014-T2 Lecture 19 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae, and John.
2013-T2 Lecture 18 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae, and John.
2015-T2 Lecture 17 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae, John Lewis,
Copyright © 0 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by Tony.
CS 367 Introduction to Data Structures Lecture 5.
Computer Science 209 Software Development Inheritance and Composition.
1 Stacks (Continued) and Queues Array Stack Implementation Linked Stack Implementation The java.util.Stack class Queue Abstract Data Type (ADT) Queue ADT.
Week 2 - Friday.  What did we talk about last time?  Computing Big Oh.
CSE 373: Data Structures and Algorithms Lecture 2: Queues.
Iterators, Iterator, and Iterable 2015-T2 Lecture 8 School of Engineering and Computer Science, Victoria University of Wellington COMP 103 Thomas Kuehne.
IMPLEMENTING ARRAYLIST COMP 103. RECAP  Comparator and Comparable  Brief look at Exceptions TODAY  Abstract Classes - but note that the details are.
Copyright © Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by Tony.
2015-T2 Lecture 19 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae, and John.
“The desire for safety stands against every great and noble enterprise.” – Tacitus Thought for the Day.
2014-T2 Lecture 18 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae, and John.
1 Example: LinkedStack LinkedStack UML Class Diagram LinkedStack Class LinkedStack Attributes/Constructor LinkedStack Methods LinkedStack iterator method.
1 Queues (Continued) Queue ADT Linked queue implementation Array queue implementation Circular array queue implementation Deque Reading L&C , 9.3.
Click to edit Master text styles Stacks Data Structure.
COMP 103 Maps and Queues. RECAP  Iterators (for-each loop)  Bag, Sets, and Stacks - a class, not interface TODAY  Maps and Queues 2 RECAP-TODAY QUICK.
Chapter 3 Lists, Stacks, Queues. Abstract Data Types A set of items – Just items, not data types, nothing related to programming code A set of operations.
COMP 103 Linked Structures
Linked Structures – Part 2
Some Collections: BAGS, SETS, and STACKS
CSE 373: Data Structures and Algorithms
Stacks and Queues.
ADT list.
Chapter 24 Implementing Lists, Stacks, Queues, and Priority Queues
More Data Structures (Part 1)
Lecture 16 Stacks and Queues CSE /26/2018.
Stacks, Queues, and Deques
Ordered Structures Wellesley College CS230 Lecture 10
Lecture 16 Stacks and Queues CSE /26/2018.
Presentation transcript:

COMP 103 Linked Lists

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

COMP 103 Linked Stack and Linked Queue

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

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