CS 1020 Data Structures and Algorithms I Lecture

  • Slides: 82
Download presentation
CS 1020 Data Structures and Algorithms I Lecture Note #10 List ADT & Linked

CS 1020 Data Structures and Algorithms I Lecture Note #10 List ADT & Linked Lists

Objectives 1 2 3 4 • Able to define a List ADT • Able

Objectives 1 2 3 4 • Able to define a List ADT • Able to implement a List ADT with array • Able to implement a List ADT with linked list • Able to use Java API Linked. List class [CS 1020 Lecture 10: List ADT & Linked Lists] 2

References Book • List ADT: Chapter 4, pages 227 to 233 • An array-based

References Book • List ADT: Chapter 4, pages 227 to 233 • An array-based implementation: Chapter 4, pages 250 to 257 • Linked Lists: Chapter 5, pages 265 to 325 CS 1020 website Resources Lectures • http: //www. comp. nus. edu. sg/ ~cs 1020/2_resources/lectures. html [CS 1020 Lecture 10: List ADT & Linked Lists] 3

Programs used in this lecture q q For Array implementation of List: n List.

Programs used in this lecture q q For Array implementation of List: n List. Interface. java n List. Using. Array. java, Test. List. Using. Array. java For Linked List implementation of List: n n n List. Node. java List. Interface. java (same List. Interface. java as in array implementation) Basic. Linked. List. java, Test. Basic. Linked. List 1. java, Test. Basic. Linked. List 2. java Enhanced. List. Interface. java Enhanced. Linked. List. java, Test. Enhanced. Linked. List. java Tailed. Linked. List. java, Test. Tailed. Linked. List. java [CS 1020 Lecture 10: List ADT & Linked Lists] 4

Outline 1. Use of a List (Motivation) § List ADT 2. List ADT Implementation

Outline 1. Use of a List (Motivation) § List ADT 2. List ADT Implementation via Array § Adding and removing elements in an array § Time and space efficiency 3. List ADT Implementation via Linked Lists § Linked list approach § List. Node class: forming a linked list with List. Node § Basic. Linked. List 4. More Linked Lists § Enhanced. Linked. List, Tailed. Linked. List 5. Other Variants § Circular. Linked. List, Doubly. Linked. List 6. Java API: Linked. List class 7. Summary [CS 1020 Lecture 10: List ADT & Linked Lists] 5

1 Use of a List Motivation

1 Use of a List Motivation

1. Use of a List Motivation q List is one of the most basic

1. Use of a List Motivation q List is one of the most basic types of data collection § For example, list of groceries, list of modules, list of friends, § etc. In general, we keep items of the same type (class) in one list q Typical Operations on a data collection § Add data § Remove data § Query data § The details of the operations vary from application to application. The overall theme is the management of data [CS 1020 Lecture 10: List ADT & Linked Lists] 7

1. Use of a List ADT of a List (1/3) q A list ADT

1. Use of a List ADT of a List (1/3) q A list ADT is a dynamic linear data structure § A collection of data items, accessible one after another starting from the beginning (head) of the list You will learn non- q Examples of List ADT operations: § § § § Create an empty list Determine whether a list is empty Determine number of items in the list Add an item at a given position Remove an item at a position Remove all items Read an item from the list at a position linear data structures such as trees and graphs in CS 2010. q The next slide on the basic list interface does not have all the above operations… we will slowly build up these operations in list beyond the basic list. [CS 1020 Lecture 10: List ADT & Linked Lists] 8

1. Use of a List ADT of a List (2/3) import java. util. *;

1. Use of a List ADT of a List (2/3) import java. util. *; public interface public boolean public int public E public boolean public void public E public void List. Interface. java List. Interface <E> { is. Empty(); size(); get. First() throws No. Such. Element. Exception; contains(E item); add. First(E item); remove. First() throws No. Such. Element. Exception; print(); } q The List. Interface above defines the operations (methods) we would like to have in a List ADT q The operations shown here are just a small sample. An actual List ADT usually contains more operations. [CS 1020 Lecture 10: List ADT & Linked Lists] 9

1. Use of a List ADT of a List (3/3) q We will examine

1. Use of a List ADT of a List (3/3) q We will examine 2 implementations of list ADT, both using the List. Interface shown in the previous slide To be discussed in section 2. Contractual obligations: Java Arrays List ADT 1. Create empty list 2. Determine … 3. Add an item Linked Lists To be discussed in section 3: Basic Linked List … ADT [CS 1020 Lecture 10: List ADT & Linked Lists] Implementations 10

2 List Implementation via Array Fixed-size list

2 List Implementation via Array Fixed-size list

2. List Implementation: Array (1/9) q This is a straight-forward approach q Use Java

2. List Implementation: Array (1/9) q This is a straight-forward approach q Use Java array of a sequence of n elements num_nodes n arr : array[0. . m] of locations a 0 a 1 a 2 0 1 [CS 1020 Lecture 10: List ADT & Linked Lists] 2 ……… an-1 unused m 12

2. List Implementation: Array (2/9) q We now create a class List. Using. Array

2. List Implementation: Array (2/9) q We now create a class List. Using. Array as an implementation of the interface List. Interface (a userdefined interface, as defined in slide 9) <<interface>> List. Interface List. Using. Array - MAXSIZE - num_nodes - arr implements + is. Empty() + size() + get. First() + contains(E item) + add. First(E item) + remove. First() + print() Representing an interface in UML diagrams Legend: implements [CS 1020 Lecture 10: List ADT & Linked Lists] 13

2. List Implementation: Array (3/9) List. Using. Array. java import java. util. *; class

2. List Implementation: Array (3/9) List. Using. Array. java import java. util. *; class List. Using. Array <E> implements List. Interface <E> { private static final int MAXSIZE = 1000; private int num_nodes = 0; private E[] arr = (E[]) new Object[MAXSIZE]; public boolean is. Empty() { return num_nodes==0; } public int size() { return num_nodes; } public E get. First() throws No. Such. Element. Exception { if (num_nodes == 0) throw new No. Such. Element. Exception("can't get from an empty list"); else return arr[0]; } public boolean contains(E item) { for (int i = 0; i < num_nodes; i++) if (arr[i]. equals(item)) return true; return false; } [CS 1020 Lecture 10: List ADT & Linked Lists] Code continued in slide 17 14

2. List Implementation: Array (4/9) q For insertion into first position, need to shift

2. List Implementation: Array (4/9) q For insertion into first position, need to shift “right” (starting from the last element) to create room Example: add. First(“it”) num_nodes 8 arr a 0 a 1 a 2 a 3 a 4 a 5 a 6 a 7 Step 2 : Write into gap Step 1 : Shift right num_nodes 89 ait 0 a 1 a 2 a 3 a 4 a 5 a 6 a 7 Step 3 : Update num_nodes [CS 1020 Lecture 10: List ADT & Linked Lists] 15

2. List Implementation: Array (5/9) q For deletion of first element, need to shift

2. List Implementation: Array (5/9) q For deletion of first element, need to shift “left” (starting from the first element) to close gap Example: remove. First() num_nodes 8 arr a 0 a 1 a 2 a 3 a 4 a 5 a 6 a 7 Step 1 : Close Gap num_nodes 87 a 1 a 2 a 3 a 4 a 5 a 6 a 7 Step 2 : Update num_nodes unused Need to maintain num_nodes so that program would not access beyond the valid data. [CS 1020 Lecture 10: List ADT & Linked Lists] 16

2. List Implementation: Array (6/9) public void add. First(E item) throws Index. Out. Of.

2. List Implementation: Array (6/9) public void add. First(E item) throws Index. Out. Of. Bounds. Exception { if (num_nodes == MAXSIZE) throw new Index. Out. Of. Bounds. Exception("insufficient space for add"); for (int i = num_nodes-1; i >= 0; i--) arr[i+1] = arr[i]; // to shift elements to the right arr[0] = item; num_nodes++; // update num_nodes } public E remove. First() throws No. Such. Element. Exception { if (num_nodes == 0) throw new No. Such. Element. Exception("can't remove from an empty list"); else { E tmp = arr[0]; for (int i = 0; i<num_nodes-1; i++) arr[i] = arr[i+1]; // to shift elements to the left num_nodes--; // update num_nodes return tmp; } print() method not shown } here. Refer to program. List. Using. Array. java [CS 1020 Lecture 10: List ADT & Linked Lists] 17

2. Testing Array Implementation (7/9) import java. util. *; public class Test. List. Using.

2. Testing Array Implementation (7/9) import java. util. *; public class Test. List. Using. Array { public static void main(String [] args) throws No. Such. Element. Exception { List. Using. Array <String> list = new List. Using. Array <String>(); list. add. First("aaa"); list. add. First("bbb"); List is: list. add. First("ccc"); ccc, bbb, aaa. list. print(); Testing removal System. out. println("Testing removal"); list. remove. First(); list. print(); if (list. contains("aaa")) list. add. First("xxxx"); list. print(); List is: bbb, aaa. List is: xxxx, bbb, aaa. } } [CS 1020 Lecture 10: List ADT & Linked Lists] Test. List. Using. Array. java 18

2. Analysis of Array Impln of List (8/9) n Question: Time Efficiency? q Retrieval:

2. Analysis of Array Impln of List (8/9) n Question: Time Efficiency? q Retrieval: get. First() n q Insertion: add. First(E item) n q Always fast with 1 read operation Shifting of all n items – bad! Insertion: add(int index, E item) n Inserting into the specified position (not shown in List. Using. Array. java) q q q Deletion: remove. First(E item) n q Best case: No shifting of items (add to the last place) Worst case: Shifting of all items (add to the first place) Shifting of all n items – bad! Deletion: remove(int index) n Delete the item at the specified position (not shown in List. Using. Array. java) q q Best case: No shifting of items (delete the last item) Worst case: Shifting of all items (delete the first item) [CS 1020 Lecture 10: List ADT & Linked Lists] 19

2. Analysis of Array Impln of List (9/9) n Question: What is the Space

2. Analysis of Array Impln of List (9/9) n Question: What is the Space Efficiency? q q Size of array collection limited by MAXSIZE Problems n n Idea: make MAXSIZE a variable, and create/copy to a larger array whenever the array runs out of space q q n We don’t always know the maximum size ahead of time If MAXSIZE is too liberal, unused space is wasted If MAXSIZE is too conservative, easy to run out of space No more limits on size But copying overhead is still a problem When to use such a list? q q For a fixed-size list, an array is good enough! For a variable-size list, where dynamic operations such as insertion/deletion are common, an array is a poor choice; better alternative – Linked List [CS 1020 Lecture 10: List ADT & Linked Lists] 20

3 List Implementation via Linked List Variable-size list

3 List Implementation via Linked List Variable-size list

3. 1 List Implementation: Linked List (1/3) q Recap when using an array. .

3. 1 List Implementation: Linked List (1/3) q Recap when using an array. . . q X, A, B are elements of an array q Y is new element to be added X I want to add Y after A. I want to remove A. [CS 1020 Lecture 10: List ADT & Linked Lists] A Unused spaces B Y 22

3. 1 List Implementation: Linked List (2/3) q Now, we see the (add) action

3. 1 List Implementation: Linked List (2/3) q Now, we see the (add) action with linked list… q X, A, B are nodes of a linked list q Y is new node to be added X I want to add Y after A. A B Y ? [CS 1020 Lecture 10: List ADT & Linked Lists] 23

3. 1 List Implementation: Linked List (3/3) q Now, we see the (remove) action

3. 1 List Implementation: Linked List (3/3) q Now, we see the (remove) action with linked list… X I want to remove A …. [CS 1020 Lecture 10: List ADT & Linked Lists] A B Node A becomes a garbage. To be removed during garbage collection. 24

3. 2 Linked List Approach (1/4) q Idea q Each element in the list

3. 2 Linked List Approach (1/4) q Idea q Each element in the list is stored in a node, which also contains a next pointer q Allow elements in the list to occupy non-contiguous memory q Order the nodes by associating each with its neighbour(s) element next ai+1 This is one node of the collection… element next ak [CS 1020 Lecture 10: List ADT & Linked Lists] … … and this one comes after it in the collection (most likely not occupying contiguous memory that is next to the previous node). Next pointer of this node is “null”, i. e. it has no next neighbour. 25

3. 2 Linked List Approach (2/4) q Recap: Object References (1/2) q Note the

3. 2 Linked List Approach (2/4) q Recap: Object References (1/2) q Note the difference between primitive data types and reference data types int x = 20; Integer y = new Integer(20); x 20 y 20 Integer String z = new String("hi th"); z h i t h String q An instance (object) of a class only comes into existence (constructed) when the new operator is applied q A reference variable only contains a reference or pointer to an object. [CS 1020 Lecture 10: List ADT & Linked Lists] 26

3. 2 Linked List Approach (3/4) q Recap: Object References (2/2) q Look at

3. 2 Linked List Approach (3/4) q Recap: Object References (2/2) q Look at it in more details: Integer y = new Integer(20); Integer w; w = new Integer(20); if (w == y) System. out. println("1. w == y"); y 20 Integer w w = y; 20 Integer if (w == y) System. out. println("2. w == y"); q Output: 2. w == y [CS 1020 Lecture 10: List ADT & Linked Lists] 27

3. 2 Linked List Approach (4/4) q Quiz: Which is the right representation of

3. 2 Linked List Approach (4/4) q Quiz: Which is the right representation of e? class Employee { private String name; private int salary; // etc. } (A) e (C) � Employee e = new Employee("Alan", 2000); Alan e 2000 Alan 2000 [CS 1020 Lecture 10: List ADT & Linked Lists] (B) e (D) e Alan 2000 28

3. 3 List. Node (using generic) class List. Node <E> { /* data attributes

3. 3 List. Node (using generic) class List. Node <E> { /* data attributes */ private E element; private List. Node <E> next; List. Node. java element next /* constructors */ public List. Node(E item) { this(item, null); } public List. Node(E item, List. Node <E> n) { element = item; next = n; } /* get the next List. Node */ public List. Node <E> get. Next() { return next; } /* get the element of the List. Node */ public E get. Element() { return element; } /* set the next reference */ public void set. Next(List. Node <E> n) { next = n }; } Mark this slide – You may need to refer to it later when we study the different variants of linked list. [CS 1020 Lecture 10: List ADT & Linked Lists] 29

3. 4 Forming a Linked List (1/3) q For a sequence of 4 items

3. 4 Forming a Linked List (1/3) q For a sequence of 4 items < a 0, a 1, a 2, a 3 > head represents null a 0 a 1 a 2 a 3 We need a head to indicate where the first node is. From the head we can get to the rest. [CS 1020 Lecture 10: List ADT & Linked Lists] 30

3. 4 Forming a Linked List (2/3) q For a sequence of 4 items

3. 4 Forming a Linked List (2/3) q For a sequence of 4 items < a 0, a 1, a 2, a 3 > List. Node <String> node 3 node 2 node 1 head = = new new Can the code be rewritten without using these object references node 1, node 2, node 3? node 1 head a 0 [CS 1020 Lecture 10: List ADT & Linked Lists] a 1 List. Node <String>("a 3", <String>("a 2", <String>("a 1", <String>("a 0", null); node 3); node 2); node 1); No longer needed after list is built. node 2 a 2 node 3 a 3 31

3. 4 Forming a Linked List (3/3) q Alternatively we can form the linked

3. 4 Forming a Linked List (3/3) q Alternatively we can form the linked list as follows: q For a sequence of 4 items < a 0, a 1, a 2, a 3 >, we can build as follows: Linked. List <String> list = new Linked. List <String>(); list. add. First(“a 3”); I don’t care how list. add. First(“a 2”); add. First() is list. add. First(“a 1”); implemented list. add. First(“a 0”); list Is this better than the code in previous slide? head a 0 [CS 1020 Lecture 10: List ADT & Linked Lists] a 1 a 2 a 3 32

3. 5 Basic Linked List (1/7) n Using List. Node to define Basic. Linked.

3. 5 Basic Linked List (1/7) n Using List. Node to define Basic. Linked. List. java import java. util. *; class Basic. Linked. List <E> implements List. Interface <E> { private List. Node <E> head = null; private int num_nodes = 0; public boolean is. Empty() { return (num_nodes == 0); } public int size() { return num_nodes; } public E get. First() throws No. Such. Element. Exception { if (head == null) throw new No. Such. Element. Exception("can't get from an empty list"); else return head. get. Element(); get. Element() and } get. Next() are methods in List. Node class (slide 29) public boolean contains(E item) { for (List. Node <E> n = head; n != null; n = n. get. Next()) if (n. get. Element(). equals(item)) return true; return false; } [CS 1020 Lecture 10: List ADT & Linked Lists] 33

3. 5 Basic Linked List (2/7) n The adding and removal of first element

3. 5 Basic Linked List (2/7) n The adding and removal of first element public void add. First(E item) { head = new List. Node <E> (item, head); num_nodes++; } Basic. Linked. List. java public E remove. First() throws No. Such. Element. Exception { List. Node <E> ln; if (head == null) throw new No. Such. Element. Exception("can't remove from empty list"); else { ln = head; head = head. get. Next(); get. Element() and num_nodes--; get. Next() are methods in return ln. get. Element(); List. Node class (slide 29) } } [CS 1020 Lecture 10: List ADT & Linked Lists] 34

3. 5 Basic Linked List (3/7) n public void add. First(E item) { head

3. 5 Basic Linked List (3/7) n public void add. First(E item) { head = new List. Node <E> (item, head); num_nodes++; } The add. First() method Case 0 item 1 item Before: list After: list. add. First(99) num_nodes head 0 num_nodes head 1 0 99 99 head num_nodes 1 1 2 or more items num_nodes head n 1 1 [CS 1020 Lecture 10: List ADT & Linked Lists] 2 head num_nodes 99 1 n+1 n 2 35

3. 5 Basic Linked List (4/7) n The remove. First() method Case 0 item

3. 5 Basic Linked List (4/7) n The remove. First() method Case 0 item Before: list After: list. remove. First() num_nodes head 0 1 item num_nodes head can’t remove ln head num_nodes 0 1 1 2 or more items num_nodes head ln head num_nodes n 1 2 n-1 n 1 2 public E remove. First() throws No. Such. Element. Exception { List. Node <E> ln; if (head == null) throw new No. Such. Element. Exception("can't remove"); else { ln = head; head = head. get. Next(); num_nodes--; return ln. get. Element(); } } [CS 1020 Lecture 10: List ADT & Linked Lists] 36

3. 5 Basic Linked List (5/7) n Printing of the linked list Basic. Linked.

3. 5 Basic Linked List (5/7) n Printing of the linked list Basic. Linked. List. java public void print() throws No. Such. Element. Exception { if (head == null) throw new No. Such. Element. Exception("Nothing to print. . . "); List. Node <E> ln = head; System. out. print("List is: " + ln. get. Element()); for (int i=1; i < num_nodes; i++) { ln = ln. get. Next(); System. out. print(", " + ln. get. Element()); } System. out. println(". "); } [CS 1020 Lecture 10: List ADT & Linked Lists] 37

3. 5 Test Basic Linked List #1 (6/7) n Example use #1 import java.

3. 5 Test Basic Linked List #1 (6/7) n Example use #1 import java. util. *; Test. Basic. Linked. List 1. java public class Test. Basic. Linked. List 1 { public static void main(String [] args) throws No. Such. Element. Exception { Basic. Linked. List <String> list = new Basic. Linked. List <String>(); list. add. First("aaa"); list. add. First("bbb"); list. add. First("ccc"); list. print(); System. out. println("Testing removal"); list. remove. First(); List is: ccc, bbb, aaa. list. print(); if (list. contains("aaa")) list. add. First("xxxx"); list. print(); Testing removal List is: bbb, aaa. List is: xxxx, bbb, aaa. } } [CS 1020 Lecture 10: List ADT & Linked Lists] 38

3. 5 Test Basic Linked List #2 (7/7) n Example use #2 Test. Basic.

3. 5 Test Basic Linked List #2 (7/7) n Example use #2 Test. Basic. Linked. List 2. java import java. util. *; public class Test. Basic. Linked. List 2 { public static void main(String [] args) throws No. Such. Element. Exception { Basic. Linked. List <Integer> list = new Basic. Linked. List <Integer>(); list. add. First(34); list. add. First(12); list. add. First(9); list. print(); List is: 9, 12, 34. Testing removal List is: 12, 34. System. out. println("Testing removal"); list. remove. First(); list. print(); } } [CS 1020 Lecture 10: List ADT & Linked Lists] 39

4 More Linked Lists Exploring variants of linked list

4 More Linked Lists Exploring variants of linked list

4. Linked Lists: Variants Basic. Linked. List OVERVIEW! implements - head - num_nodes -a

4. Linked Lists: Variants Basic. Linked. List OVERVIEW! implements - head - num_nodes -a s ha List. Node - element - next Enhanced. Linked. List im ple m en ts - head - num_nodes a ts en m e l p im Tailed. Linked. List - head - tail - num_nodes [CS 1020 Lecture 10: List ADT & Linked Lists] + is. Empty() + size() + get. First() + contains(E item) + add. First(E item) + remove. First() + print() <<interface>> Enhanced. List. Interface s- ha + get. Next() + get. Element() + set. Next(List. Node <E> curr) has-a <<interface>> List. Interface + is. Empty() + size() + get. First() + contains(E item) + add. First(E item) + remove. First() + print() + get. Head() + add. After(List. Node <E> curr, E item) + remove. After(List. Node <E> curr) + remove( E item) 41

4. 1 Enhanced Linked List (1/11) n We explore different implementations of Linked List

4. 1 Enhanced Linked List (1/11) n We explore different implementations of Linked List q Basic Linked List, Tailed Linked List, Circular Linked List, Doubly Linked List, etc. n When nodes are to be inserted to the middle of the linked list, Basic. Linked. List (BLL) is not good enough. n For example, BLL offers only insertion at the front of the list. If the items in the list must always be sorted according to some key values, then we must be able to insert at the right place. n We will enhance BLL to include some additional methods. We shall call this Enhanced Linked List (ELL). q (Note: We could have made ELL a subclass of BLL, but here we will create ELL from scratch instead. ) [CS 1020 Lecture 10: List ADT & Linked Lists] 42

4. 1 Enhanced Linked List (2/11) n We use a new interface file: import

4. 1 Enhanced Linked List (2/11) n We use a new interface file: import java. util. *; Enhanced. List. Interface. java public interface Enhanced. List. Interface <E> { public public boolean int E boolean void E void is. Empty(); size(); get. First() throws No. Such. Element. Exception; contains(E item); add. First(E item); remove. First() throws No. Such. Element. Exception; print(); New public List. Node <E> get. Head(); public void add. After(List. Node <E> current, E item); public E remove. After(List. Node <E> current) throws No. Such. Element. Exception; public E remove(E item) throws No. Such. Element. Exception; } [CS 1020 Lecture 10: List ADT & Linked Lists] 43

4. 1 Enhanced Linked List (3/11) Enhanced. Linked. List. java import java. util. *;

4. 1 Enhanced Linked List (3/11) Enhanced. Linked. List. java import java. util. *; class Enhanced. Linked. List <E> implements Enhanced. List. Interface <E> { private List. Node <E> head = null; private int num_nodes = 0; public public boolean is. Empty() { return (num_nodes == 0); } int size() { return num_nodes; } Same as in E get. First() {. . . } Basic. Linked. List. java boolean contains(E item) {. . . } void add. First(E item) {. . . } E remove. First() throws No. Such. Element. Exception {. . . }; void print() throws No. Such. Element. Exception {. . . }; public List. Node <E> get. Head() { return head; } public void add. After(List. Node <E> current, E item) { if (current != null) current. set. Next(new List. Node <E> (item, current. get. Next())); else // insert item at front head = new List. Node <E> (item, head); num_nodes++; } To continue on next slide [CS 1020 Lecture 10: List ADT & Linked Lists] 44

4. 1 Enhanced Linked List (4/11) public void add. After(List. Node <E> current, E

4. 1 Enhanced Linked List (4/11) public void add. After(List. Node <E> current, E item) { if (current != null) { current. set. Next(new List. Node <E>(item, current. get. Next())); } else { // insert item at front head = new List. Node <E> (item, head); } num_nodes++; } current item head num_nodes 4 5 a 0 [CS 1020 Lecture 10: List ADT & Linked Lists] a 1 a 2 a 3 45

4. 1 Enhanced Linked List (5/11) Enhanced. Linked. List. java public E remove. After(List.

4. 1 Enhanced Linked List (5/11) Enhanced. Linked. List. java public E remove. After(List. Node <E> current) throws No. Such. Element. Exception { E temp; if (current != null) { List. Node <E> next. Ptr = current. get. Next(); if (next. Ptr != null) { temp = next. Ptr. get. Element(); current. set. Next(next. Ptr. get. Next()); num_nodes--; return temp; } else throw new No. Such. Element. Exception("No next node to remove"); } else { // if current is null, assume we want to remove head if (head != null) { temp = head. get. Element(); head = head. get. Next(); num_nodes--; return temp; } else throw new No. Such. Element. Exception("No next node to remove"); } } [CS 1020 Lecture 10: List ADT & Linked Lists] 46

4. 1 Enhanced Linked List (6/11) public E remove. After(List. Node <E> current) throws.

4. 1 Enhanced Linked List (6/11) public E remove. After(List. Node <E> current) throws. . . { E temp; if (current != null) { List. Node<E> next. Ptr = current. get. Next(); if (next. Ptr != null) { temp = next. Ptr. get. Element(); current. set. Next(next. Ptr. get. Next()); num_nodes--; return temp; } else throw new No. Such. Element. Exception(". . . "); } else {. . . } } current next. Ptr head temp a 2 num_nodes 4 3 a 0 [CS 1020 Lecture 10: List ADT & Linked Lists] a 1 a 2 a 3 47

4. 1 Enhanced Linked List (7/11) public E remove. After(List. Node <E> current) throws.

4. 1 Enhanced Linked List (7/11) public E remove. After(List. Node <E> current) throws. . . { E temp; if (current != null) {. . . } else { // if current is null, we want to remove head if (head != null) { temp = head. get. Element(); head = head. get. Next(); num_nodes--; return temp; } else throw new No. Such. Element. Exception(". . . "); } null current temp head a 0 num_nodes 4 3 a 0 [CS 1020 Lecture 10: List ADT & Linked Lists] a 1 a 2 a 3 48

4. 1 Enhanced Linked List (8/11) n remove(E item) q q Search for item

4. 1 Enhanced Linked List (8/11) n remove(E item) q q Search for item in list Re-using remove. After() method Enhanced. Linked. List. java public E remove(E item) throws No. Such. Element. Exception { // Write your code below. . . // Should make use of remove. After() method. } } [CS 1020 Lecture 10: List ADT & Linked Lists] 49

4. 1 Enhanced Linked List (9/11) public E remove(E item) throws. . . {

4. 1 Enhanced Linked List (9/11) public E remove(E item) throws. . . { } item prev a 2 curr head num_nodes 4 3 a 0 [CS 1020 Lecture 10: List ADT & Linked Lists] a 1 a 2 a 3 50

4. 1 Test Enhanced Linked List (10/11) import java. util. *; Test. Enhanced. Linked.

4. 1 Test Enhanced Linked List (10/11) import java. util. *; Test. Enhanced. Linked. List. java public class Test. Enhanced. Linked. List { public static void main(String [] args) throws No. Such. Element. Exception { Enhanced. Linked. List <String> list = new Enhanced. Linked. List <String>(); System. out. println("Part 1"); list. add. First("aaa"); list. add. First("bbb"); list. add. First("ccc"); list. print(); System. out. println("Part 2"); List. Node <String> current = list. get. Head(); list. add. After(current, "xxx"); list. add. After(current, "yyy"); list. print(); [CS 1020 Lecture 10: List ADT & Linked Lists] 51

4. 1 Test Enhanced Linked List (11/11) // (continue from previous slide) Test. Enhanced.

4. 1 Test Enhanced Linked List (11/11) // (continue from previous slide) Test. Enhanced. Linked. List. java System. out. println(); System. out. println("Part 3"); current = list. get. Head(); if (current != null) { current = current. get. Next(); list. remove. After(current); } list. print(); System. out. println("Part 4"); list. remove. After(null); list. print(); } } [CS 1020 Lecture 10: List ADT & Linked Lists] 52

4. Linked Lists: Variants Basic. Linked. List OVERVIEW! implements - head - num_nodes -a

4. Linked Lists: Variants Basic. Linked. List OVERVIEW! implements - head - num_nodes -a s ha List. Node - element - next Enhanced. Linked. List im ple m en ts - head - num_nodes a ts en m e l p im Tailed. Linked. List - head - tail - num_nodes [CS 1020 Lecture 10: List ADT & Linked Lists] + is. Empty() + size() + get. First() + contains(E item) + add. First(E item) + remove. First() + print() <<interface>> Enhanced. List. Interface s- ha + get. Next() + get. Element() + set. Next(List. Node <E> curr) has-a <<interface>> List. Interface + is. Empty() + size() + get. First() + contains(E item) + add. First(E item) + remove. First() + print() + get. Head() + add. After(List. Node <E> curr, E item) + remove. After(List. Node <E> curr) + remove( E item) 53

4. 2 Tailed Linked List (1/10) n We further improve on Enhanced Linked List

4. 2 Tailed Linked List (1/10) n We further improve on Enhanced Linked List q q n To address the issue that adding to the end is slow Add an extra data member called tail Extra data member means extra maintenance too – no free lunch! (Note: We could have created this Tailed Linked List as a subclass of Enhanced Linked List, but here we will create it from scratch. ) Difficulty: Learn to take care of ALL cases of updating. . . tail head num_nodes 4 a 0 [CS 1020 Lecture 10: List ADT & Linked Lists] a 1 a 2 a 3 54

4. 2 Tailed Linked List (2/10) n n A new data member: tail Extra

4. 2 Tailed Linked List (2/10) n n A new data member: tail Extra maintenance needed, eg: see add. First() import java. util. *; Tailed. Linked. List. java class Tailed. Linked. List <E> implements Enhanced. List. Interface <E> { private List. Node <E> head = null; private List. Node <E> tail = null; private int num_nodes = 0; public List. Node <E> get. Tail() { return tail; } public void add. First(E item) { head = new List. Node <E> (item, head); num_nodes++; if (num_nodes == 1) tail = head; } [CS 1020 Lecture 10: List ADT & Linked Lists] New code 55

4. 2 Tailed Linked List (3/10) n With the new member tail, can add

4. 2 Tailed Linked List (3/10) n With the new member tail, can add to the end of the list directly by creating a new method add. Last() q Remember to update tail public void add. Last(E item) { if (head != null) { tail. set. Next(new List. Node <E> (item)); tail = tail. get. Next(); } else { tail = new List. Node <E> (item); head = tail; } num_nodes++; } [CS 1020 Lecture 10: List ADT & Linked Lists] Tailed. Linked. List. java 56

4. 2 Tailed Linked List (4/10) Tailed. Linked. List. java public void add. Last(E

4. 2 Tailed Linked List (4/10) Tailed. Linked. List. java public void add. Last(E item) { if (head != null) { tail. set. Next(new List. Node <E> (item)); tail = tail. get. Next(); } else { tail = new List. Node <E> (item); head = tail; } num_nodes++; } n Case 1: head != null head n Case 2: head == null tail head a b … g y New node [CS 1020 Lecture 10: List ADT & Linked Lists] y New node 57

4. 2 Tailed Linked List (5/10) n add. After() method Tailed. Linked. List. java

4. 2 Tailed Linked List (5/10) n add. After() method Tailed. Linked. List. java public void add. After(List. Node <E> current, E item) { if (current != null) { current. set. Next(new List. Node <E> (item, current. get. Next())); if (current == tail) tail = current. get. Next(); } else { // add to the front of the list head = new List. Node <E> (item, head); if (tail == null) tail = head; } num_nodes++; } We may replace our earlier add. First() method (in slide 55) with a simpler one that merely calls add. After(). How? Hint: Study the remove. First() method (slide 62). [CS 1020 Lecture 10: List ADT & Linked Lists] 58

4. 2 Tailed Linked List (6/10) Tailed. Linked. List. java public void add. After(List.

4. 2 Tailed Linked List (6/10) Tailed. Linked. List. java public void add. After(List. Node <E> current, E item) { if (current != null) { current. set. Next(new List. Node <E> (item, current. get. Next())); if (current == tail) tail = current. get. Next(); } else {. . . } num_nodes++; } n Case 1 A q n current != null; current != tail Case 1 B q current != null; current == tail current … p q y New node [CS 1020 Lecture 10: List ADT & Linked Lists] … … p tail q y New node 59

4. 2 Tailed Linked List (7/10) Tailed. Linked. List. java public void add. After(List.

4. 2 Tailed Linked List (7/10) Tailed. Linked. List. java public void add. After(List. Node <E> current, E item) { if (current != null) {. . . } else { // add to the front of the list head = new List. Node <E> (item, head); if (tail == null) tail = head; } num_nodes++; } n Case 2 A q n current == null; tail != null head current a b Case 2 B q current == null; tail == null head tail current … y y New node [CS 1020 Lecture 10: List ADT & Linked Lists] 60

4. 2 Tailed Linked List (8/10) n remove. After() method Tailed. Linked. List. java

4. 2 Tailed Linked List (8/10) n remove. After() method Tailed. Linked. List. java public E remove. After(List. Node <E> current) throws No. Such. Element. Exception { E temp; if (current != null) { List. Node <E> next. Ptr = current. get. Next(); if (next. Ptr != null) { temp = next. Ptr. get. Element(); current. set. Next(next. Ptr. get. Next()); num_nodes--; if (next. Ptr. get. Next() == null) // last node is removed tail = current; return temp; else throw new No. Such. Element. Exception(". . . "); else { // if current == null, we want to remove head if (head != null) { temp = head. get. Element(); head = head. get. Next(); num_nodes--; if (head == null) tail = null; return temp; } else throw new No. Such. Element. Exception(". . . "); } } [CS 1020 Lecture 10: List ADT & Linked Lists] 61

4. 2 Tailed Linked List (9/10) n remove. First() method q remove. First() is

4. 2 Tailed Linked List (9/10) n remove. First() method q remove. First() is a special case in remove. After() public E remove. First() throws No. Such. Element. Exception { return remove. After(null); } Tailed. Linked. List. java n Study the full program Tailed. Linked. List. java on the module website on your own. [CS 1020 Lecture 10: List ADT & Linked Lists] 62

4. 2 Test Tailed Linked List (10/10) import java. util. *; Test. Tailed. Linked.

4. 2 Test Tailed Linked List (10/10) import java. util. *; Test. Tailed. Linked. List. java public class Test. Tailed. Linked. List { public static void main(String [] args) throws No. Such. Element. Exception { Tailed. Linked. List <String> list = new Tailed. Linked. List <String>(); System. out. println("Part 1"); list. add. First("aaa"); list. add. First("bbb"); list. add. First("ccc"); list. print(); System. out. println("Part 2"); list. add. Last("xxx"); list. print(); System. out. println("Part 3"); list. remove. After(null); list. print(); } } [CS 1020 Lecture 10: List ADT & Linked Lists] 63

4. Linked Lists: Variants Basic. Linked. List OVERVIEW! implements - head - num_nodes -a

4. Linked Lists: Variants Basic. Linked. List OVERVIEW! implements - head - num_nodes -a s ha List. Node - element - next Enhanced. Linked. List im ple m en ts - head - num_nodes a ts en m e l p im Difficulty: (Boundary cases) Take care of all cases of update 0 element 1 element 2 elements 3 or more elements, etc. [CS 1020 Lecture 10: List ADT & Linked Lists] + is. Empty() + size() + get. First() + contains(E item) + add. First(E item) + remove. First() + print() <<interface>> Enhanced. List. Interface s- ha + get. Next() + get. Element() + set. Next(List. Node <E> curr) has-a <<interface>> List. Interface Tailed. Linked. List - head - tail - num_nodes + is. Empty() + size() + get. First() + contains(E item) + add. First(E item) + remove. First() + print() + get. Head() + add. After(List. Node <E> curr, E item) + remove. After(List. Node <E> curr) + remove( E item) 64

5 Other Variants Other variants of linked lists

5 Other Variants Other variants of linked lists

5. 1 Circular Linked List n n There are many other possible enhancements of

5. 1 Circular Linked List n n There are many other possible enhancements of linked list Example: Circular Linked List q q q n n To allow cycling through the list repeatedly, e. g. in a round robin system to assign shared resource Add a link from tail node of the Tailed. Linked. List to point back to head node Different in linking need different maintenance – no free lunch! Difficulty: Learn to take care of ALL cases of updating, such as inserting/deleting the first/last node in a Circular Linked List Explore this on your own; write a class Circular. Linked. List tail head num_nodes 4 a 0 [CS 1020 Lecture 10: List ADT & Linked Lists] a 1 a 2 a 3 66

5. 2 Doubly Linked List (1/3) n n n In the preceding discussion, we

5. 2 Doubly Linked List (1/3) n n n In the preceding discussion, we have a “next” pointer to move forward Often, we need to move backward as well Use a “prev” pointer to allow backward traversal Once again, no free lunch – need to maintain “prev” in all updating methods Instead of List. Node class, need to create a DList. Node class that includes the additional “prev” pointer prev next x 2 node [CS 1020 Lecture 10: List ADT & Linked Lists] 67

5. 2 Doubly Linked List: DList. Node. java class DList. Node <E> { (2/3)

5. 2 Doubly Linked List: DList. Node. java class DList. Node <E> { (2/3) /* data attributes */ private E element; private DList. Node <E> prev; private DList. Node <E> next; /* constructors */ public DList. Node(E item) { this(item, null); } public DList. Node(E item, DList. Node <E> p, DList. Node <E> n) { element = item; prev = p; next = n; } /* get public the prev DList. Node */ DList. Node <E> get. Prev() { return this. prev; } the next DList. Node */ DList. Node <E> get. Next() { return this. next; } /* get the element of the List. Node */ public E get. Element() { return this. element; } /* set public the prev reference */ void set. Prev(DList. Node <E> p) { prev = p }; the next reference */ void set. Next(DList. Node <E> n) { next = n }; } [CS 1020 Lecture 10: List ADT & Linked Lists] 68

5. 2 Doubly Linked List (3/3) n An example of a doubly linked list

5. 2 Doubly Linked List (3/3) n An example of a doubly linked list tail head num_nodes 4 n n x 1 x 2 x 3 x 4 Explore this on your own. Write a class Doubly. Linked. List to implement the various linked list operations for a doubly linked list. [CS 1020 Lecture 10: List ADT & Linked Lists] 69

6 Java API: Linked. List class Using the Linked. List class

6 Java API: Linked. List class Using the Linked. List class

6 Java Class: Linked. List <E> n n n This is the class provided

6 Java Class: Linked. List <E> n n n This is the class provided by Java library This is the linked list implementation of the List interface It has many more methods than what we have discussed so far of our versions of linked lists. On the other hand, we created some methods not available in the Java library class too. Please do not confuse this library class from our class illustrated here. In a way, we open up the Java library to show you the inside working. For purposes of sit-in labs or exam, please use whichever one as you are told if stated. [CS 1020 Lecture 10: List ADT & Linked Lists] 71

6. 1 Class Linked. List: API (1/3) [CS 1020 Lecture 10: List ADT &

6. 1 Class Linked. List: API (1/3) [CS 1020 Lecture 10: List ADT & Linked Lists] 72

6. 1 Class Linked. List: API (2/3) [CS 1020 Lecture 10: List ADT &

6. 1 Class Linked. List: API (2/3) [CS 1020 Lecture 10: List ADT & Linked Lists] 73

6. 1 Class Linked. List: API (3/3) [CS 1020 Lecture 10: List ADT &

6. 1 Class Linked. List: API (3/3) [CS 1020 Lecture 10: List ADT & Linked Lists] 74

6. 2 Class Linked. List (1/2) n An example use (Page 1 of 2)

6. 2 Class Linked. List (1/2) n An example use (Page 1 of 2) import java. util. *; Test. Linked. List. API. java public class Test. Linked. List. API { static void print. List(Linked. List <Integer> alist) { System. out. print("List is: "); for (int i = 0; i < alist. size(); i++) System. out. print(alist. get(i) + "t"); System. out. println(); } // Print elements in the list and also delete them static void print. Listv 2(Linked. List <Integer> alist) { System. out. print("List is: "); while (alist. size() != 0) { System. out. print(alist. element() + "t"); alist. remove. First(); } System. out. println(); } [CS 1020 Lecture 10: List ADT & Linked Lists] 75

6. 2 Class Linked. List (2/2) n An example use (Page 2 of 2)

6. 2 Class Linked. List (2/2) n An example use (Page 2 of 2) Test. Linked. List. API. java public static void main(String [] args) { Linked. List <Integer> alist = new Linked. List <Integer> (); for (int i = 1; i <= 5; i++) alist. add(new Integer(i)); print. List(alist); System. out. println("First element: " + alist. get. First()); System. out. println("Last element: " + alist. get. Last()); alist. add. First(888); alist. add. Last(999); print. Listv 2(alist); print. List(alist); } } [CS 1020 Lecture 10: List ADT & Linked Lists] 76

Why “reinvent the wheel”? n n In a data structures course, students are often

Why “reinvent the wheel”? n n In a data structures course, students are often asked to implement well-known data structures. A question we sometimes hear from students: “Since there is the API, why do we need to learn to write our own code to implement a data structure like linked list? ” Writing the code allows you to gain an indepth understanding of the data structures and their operations The understanding will allow you to appreciate their complexity analysis (to be covered later) and use the API effectively [CS 1020 Lecture 10: List ADT & Linked Lists] 77

7 Summary (1/2) n We learn to create our own data structure q In

7 Summary (1/2) n We learn to create our own data structure q In creating our own data structure, we face 3 difficulties: 1. Re-use of codes (inheritance confusion) 2. Manipulation of pointers/references (The sequence of statements is important! With the wrong sequence, the result will be wrong. ) 3. Careful with all the boundary cases q Drawings are very helpful in understanding the cases (point 3), which then can help in knowing what can be used/manipulated (points 1 and 2) [CS 1020 Lecture 10: List ADT & Linked Lists] 78

7 Summary (2/2) n Once we can get through this lecture, the rest should

7 Summary (2/2) n Once we can get through this lecture, the rest should be smooth sailing as all the rest are similar in nature q n You should try to add more methods to our versions of Linked. List, or to extend List. Node to other type of node Please do not forget that the Java Library class is much more comprehensive than our own – for sit-in labs and exam, please use whichever one as you are told if stated. [CS 1020 Lecture 10: List ADT & Linked Lists] 79

8 Practice Exercises n n n Exercise #28: List Reversal Exercise #29: Self-Adjusting List

8 Practice Exercises n n n Exercise #28: List Reversal Exercise #29: Self-Adjusting List Exercise #30: Sorted Linked List [CS 1020 Lecture 10: List ADT & Linked Lists] 80

9 Visualising Data Structures n See http: //visualgo. net q q n Click on

9 Visualising Data Structures n See http: //visualgo. net q q n Click on “Linked List, Stack, Queue” (Non-linear data structures such as trees and graphs will be covered in CS 2010. ) See http: //www. cs. usfca. edu/~galles/visualization/Algorithms. html [CS 1020 Lecture 10: List ADT & Linked Lists] 81

End of file

End of file