Announcements. Prelude (2) Prelude (1) Data Structures and Information Systems Part 1: Data Structures. Lecture 6: Lists.

Similar documents
Topics. Java arrays. Definition. Data Structures and Information Systems Part 1: Data Structures. Lecture 3: Arrays (1)

ITI Introduction to Computing II

COMP 250. Lecture 6. doubly linked lists. Sept. 20/21, 2017

Assignment 1. Check your mailbox on Thursday! Grade and feedback published by tomorrow.

CS 151. Linked Lists, Recursively Implemented. Wednesday, October 3, 12

Abstract Data Types - Lists Arrays implementa4on Linked- lists implementa4on

CS350: Data Structures. Doubly Linked Lists

Data Structure: Lists and Iterators. Instructor: Prof. Young-guk Ha Dept. of Computer Science & Engineering

Class 26: Linked Lists

doubly linked lists Java LinkedList

CMSC 341 Lecture 7 Lists

Lecture 12: Doubly Linked Lists

Data Structures (CS301) LAB

Spring 2008 Data Structures (CS301) LAB

COMP 250 Winter generic types, doubly linked lists Jan. 28, 2016

Insertion Sort: an algorithm for sorting an array

Programming II (CS300)

Abstract Data Types - Lists Arrays implementation Linked-lists implementation

Tutorial 2: Linked Lists

The Java Collections Framework. Chapters 7.5

Introduction to Programming in C Department of Computer Science and Engineering

+ Abstract Data Types

Homework 2: Imperative Due: 5:00 PM, Feb 15, 2019

COMP 250. Lecture 8. stack. Sept. 25, 2017

CSCI 136 Data Structures & Advanced Programming. Lecture 13 Fall 2018 Instructors: Bill 2

An Introduction to Data Structures

Lecture 4. The Java Collections Framework

Lecture 7: Implementing Lists, Version 2

CSC 172 Data Structures and Algorithms. Lecture #8 Spring 2018

COMP 250 Midterm #2 March 11 th 2013

1.00 Introduction to Computers and Engineering Problem Solving. Final Examination - May 19, 2004

Insertions and removals follow the Fist-In First-Out rule: Insertions: at the rear of the queue Removals: at the front of the queue

CS 270 Algorithms. Oliver Kullmann. Binary search. Lists. Background: Pointers. Trees. Implementing rooted trees. Tutorial

CE204 Data Structures and Algorithms Part 2

About this exam review

Elementary Data Structures: Part 1: Arrays, Lists. CSE 2320 Algorithms and Data Structures Vassilis Athitsos University of Texas at Arlington

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #29 Arrays in C

Linked Lists. Chapter 4

Implementation. Learn how to implement the List interface Understand the efficiency trade-offs between the ArrayList and LinkedList implementations

Computer Science 1 Ah

Programming 2. Topic 8: Linked Lists, Basic Searching and Sorting

Lists (Section 5) Lists, linked lists Implementation of lists in C Other list structures List implementation of stacks, queues, priority queues

9/26/2018 Data Structure & Algorithm. Assignment04: 3 parts Quiz: recursion, insertionsort, trees Basic concept: Linked-List Priority queues Heaps

CS/CE 2336 Computer Science II

CSC 172 Data Structures and Algorithms. Lecture #9 Spring 2018

Data Structures Lecture 5

CS2 Practical 1 CS2A 22/09/2004

Notes on access restrictions

10/1/2018 Data Structure & Algorithm. Circularly Linked List Doubly Linked List Priority queues Heaps

Java Collections. Readings and References. Collections Framework. Java 2 Collections. CSE 403, Spring 2004 Software Engineering

BBM 201 DATA STRUCTURES

Linked lists. Insert Delete Lookup Doubly-linked lists. Lecture 6: Linked Lists

csci 210: Data Structures Linked lists Summary Arrays vs. Lists Arrays vs. Linked Lists a[0] a[1] a[2]... null Today READING: Arrays

Data structure is an organization of information, usually in memory, for better algorithm efficiency.

Data Structures. Lecture 04 Sohail Aslam AL 1

CS2 Practical 2 CS2Ah

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

Generics. IRS W-9 Form

UNIT-1. Chapter 1(Introduction and overview) 1. Asymptotic Notations 2. One Dimensional array 3. Multi Dimensional array 4. Pointer arrays.

Programming II (CS300)

APCS Semester #1 Final Exam Practice Problems

Computer Science 136. Midterm Examination

Computer Science 210: Data Structures. Linked lists

DATA STRUCTURES AND ALGORITHMS

Lists using LinkedList

Lists and Iterators. CSSE 221 Fundamentals of Software Development Honors Rose-Hulman Institute of Technology

Queues. CITS2200 Data Structures and Algorithms. Topic 5

CS 307 Final Spring 2008

Introduction to Data Structures and Algorithms

CS1020 Data Structures and Algorithms I Lecture Note #10. List ADT & Linked Lists

CS 1316 Exam 2 Summer 2009

Data Structures and Algorithms " Arrays and Linked Lists!

Ticket Machine Project(s)

DOWNLOAD PDF LINKED LIST PROGRAMS IN DATA STRUCTURE

CH7. LIST AND ITERATOR ADTS

Linked List Practice Questions

Introduction to Programming Using Java (98-388)

Software Testing Prof. Meenakshi D Souza Department of Computer Science and Engineering International Institute of Information Technology, Bangalore

Revising CS-M41. Oliver Kullmann Computer Science Department Swansea University. Linux Lab Swansea, December 13, 2011.

Java Collections. Readings and References. Collections Framework. Java 2 Collections. References. CSE 403, Winter 2003 Software Engineering

Software Testing Prof. Rajib Mall Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur. Lecture 13 Path Testing

4.1 Ordered Lists Revisited

Topic 11 Linked Lists

Advanced Linked Lists. Doubly Linked Lists Circular Linked Lists Multi- Linked Lists

Recap. List Types. List Functionality. ListIterator. Adapter Design Pattern. Department of Computer Science 1

CH7. LIST AND ITERATOR ADTS

Introduction to Programming in C Department of Computer Science and Engineering

Topic #9: Collections. Readings and References. Collections. Collection Interface. Java Collections CSE142 A-1

Lists. CITS2200 Data Structures and Algorithms. Topic 9

ADTs, Arrays, Linked Lists

Abstract Data Types. Data Str. Client Prog. Add. Rem. Find. Show. 01/30/03 Lecture 7 1

Introduction. Reference

Object-Oriented Design Lecture 11 CS 3500 Spring 2010 (Pucella) Tuesday, Feb 16, 2010

COMP 103. Data Structures and Algorithms

LINKED LISTS cs2420 Introduction to Algorithms and Data Structures Spring 2015

Introduction to Computer Science II CS S-20 Linked Lists IV

CE204 Data Structures and Algorithms Part 1

CS 211 Programming Practicum Spring 2018

Revising CS-M41. Oliver Kullmann Computer Science Department Swansea University. Robert Recorde room Swansea, December 13, 2013.

Transcription:

Announcements MODULE WEB-SITE: http://www.csc.liv.ac.uk/ michele/teaching/comp102/comp102.html FIRST ASSIGNMENT DEADLINE: Wednesday, February 1st, 14.30, LAB 7 Boxes (late submissions to be left in the wooden box to my office door). SIGN the PLAGIARISM DECLARATION!! Data Structures and Information Systems Part 1: Data Structures Michele Zito Lecture 6: Lists. p.1/74. p.2/74 Prelude (1) Prelude (2) Before we start this part it is important to make few things clear: You will notice that the lecture material related to lists is quite extensive. Such material is meant to help you understand this rather difficult topic. What is the best approach to the study of lists? 1. Come to the lecture and, having your notes handy, highlight the slides that we will look at in the lecture. These are the core slides. You will NOT understand lists unless you go through these slides very carefully. 2. Some slides will be missed out. These additional slide contain either additional examples or algorithms that are very similar to the ones we will see in the lecture. This is particularly true for lists but it also applies to ALL forthcoming topics.. p.3/74 Before we start this part it is important to make few things clear: The understanding is that these additional slides can be studied without me going through them during a lecture. Remember that you are expected to put about 9-10 hours of your time per week on each of the modules you are attending. As to COMP102, excluding lectures and tutorials, you are expected to work about 5 more hours per week on this module. Of course if you experience any difficulty in understanding this additional material do not hesitate to contact me (or one of the tutors). (VERY IMPORTANT!!!) Assessed exercises and exam may contain questions related to ANY of the slides that are being made available.. p.4/74

Topics Lists: Motivations (1) Lists Motivation Arrays versus Lists Singly linked lists We have started to look at the ways in which can be organised in the computer memory. The simplest way in which can be organised is as a sequence of boxes arranged in contiguous memory locations. Structures of this kind are called array (the multidimensional case being essentially just a variation on the same theme). a T[] n class tag length 0 1 n 2 n 1 Fast access time and staticity are, in a sense, direct consequences of the way in which arrays are defined.. p.5/74. p.6/74 Lists: Motivation Suppose we really want to define a dynamic structure, how can we do that?? Lists: Motivation Suppose we really want to define a dynamic structure, how can we do that?? One option is, perhaps, to allocate new contiguous memory blocks as we need them. p.7/74. p.7/74

Lists: Motivation Lists: Motivation Suppose we really want to define a dynamic structure, how can we do that?? One option is, perhaps, to allocate new contiguous memory blocks as we need them... but then we need to keep track of where they are! Suppose we really want to define a dynamic structure, how can we do that?? One option is, perhaps, to allocate new contiguous memory blocks as we need them... but then we need to keep track of where they are! Maybe we can associate this information with the individual blocks!. p.7/74. p.7/74 Lists: Motivation More precise definition Suppose we really want to define a dynamic structure, how can we do that?? One option is, perhaps, to allocate new contiguous memory blocks as we need them... but then we need to keep track of where they are! Maybe we can associate this information with the individual blocks! Lists provide a simple and general way to solve this problem! A list is defined as a sequence of components (of the same type) with the following properties the length of the list equals the number of its components (a list of length zero if often called empty list). the components of the list are ordered so that it is defined the notion of first element, second element,...ith element of the list. Operations are defined to allow: Inserting an element at a specified position into a list Locating the position of a specified element Retrieving an element from a specified position in a list Deleting an element at a specified position in a list Printing all elements in a list. p.7/74. p.8/74

Arrays versus Lists Implementation The number of components of an array is fixed when the array is created In contrast, the number of elements in a list can be varied by adding or removing elements All components of an array can be accessed in constant time through their index, but the same needn t be true for the elements of a list. To keep the structure dynamical, a list is usually constructed by allocating space for the list components and then use a (language-dependent) mechanism for linking together different components. Since the list components are stored in completely unrelated parts of the computer memory, the list can be easily expanded (or contracted) by handling individual components and the way they are linked together. In the forthcoming slides we will make these concepts more precise.. p.9/74. p.10/74 Self-referential classes To join list elements together, each element must be an object of a self-referential class A self-referential class is one that contains a reference member that refers to an object of the same class class Node { protected Object ; / / Any type of here protected Node ; / / Another o b j e c t of the same typ / / Constructor and methods go here Here we have used the access level specifier protected, which allows the class itself, subclasses, and all classes in the same package to access the members.. p.11/74 Linking objects An object of a self-referential class can be seen as having two parts: the part, containing the used by an application, in our case stored in the field of a Node object the link part which is a reference to another object of the same class, in our case stored in the field of a Node object Later, we will see that we can have more than one link to other objects so that we can create more complex structures. p.12/74

(Singly) Linked lists The life of a (singly) linked list We can know bring all of this together! A (singly) linked list is a linear collection (sequence) of self-referential objects, called nodes, connected by references. A (singly) linked list has a (a reference to the first element) from which we can access the first element of the list. We indicate that there is no object with a reference to A (singly) linked list starts off empty (i.e. refers to ) Elements can be inserted at the front ( will then refer to new element) at the end (new element will then refer to ) at any place between elements (references must be adjusted so that the chain does not break) Elements can be deleted (adjusting references). p.13/74. p.14/74 Node implementation (1) Let us flesh out the implementation of the Node class by adding constructor, accessor, and mutator methods: class Node { p rotected Object ; / / Data stored i n node p rotected Node ; / / Link to node Our first constructor takes (a reference to) an arbitrary object and (a reference to) the item in the list and constructs a new Node object out of this information p u b l i c Node ( Object o, Node item ) { = o ; / / Set = item ; / / Set reference to item Node implementation (2) If we want to store elements of a primitive type in a Node we would have to make use of a wrapper class It might be more convenient to have additional constructors which do this job for us: p u b l i c Node ( i n t number, Node item ) { = new I n t e g e r ( number ) ; = item ; We could systematically add similar constructors for all other primitive types like char, float, etc.. p.15/74. p.16/74

Node implementation (3) Next, we add some accessors to the Node class We provide accessors for both attributes of an instance of the Node class: p u b l i c Object getdata ( ) { r e t u r n ( ) ; p u b l i c Node getnext ( ) { r e t u r n ( ) ; As we have provided a special constructor for nodes storing values of type int, we may also add a special accessor in case the attribute stores a value of type int: p u b l i c i n t g e tintdata ( ) { r e t u r n ( ( ( I n t e g e r ) ). i n t V a l u e ( ) ) ; Note all these methods are public Node implementation (4) Finally, we also add some mutators (i.e. methods that change the value of some attribute in the given class) to the Node class. Again, we provide mutators for both attributes of an instance of the Node class, as well as a special mutator in the case we want to an integer value in a node: p u b l i c void setdata ( Object o ) { = o ; p u b l i c void setnext ( Node item ) { = item ; p u b l i c void s e t I n t D a t a ( i n t number ) { = new I n t e g e r ( number ) ; / / End of Node class. p.17/74. p.18/74 Linked list implementation (1) Linked list implementation (2) Next we implement (singly) linked lists using the following LinkedList class By definition, a linked list has a (a reference to the first element) from which we can access the first element of the list p u b l i c class L i n k e d L i s t { p rotected Node ; / / Reference to f i r s t eleme / / Constructor creates an empty l i s t p u b l i c L i n k e d L i s t ( ) { = n u l l ; Note that we have made a design choice here by the way an empty list is constructed Again we can add additional constructors, for example, a constructor that initialises a new instance of LinkedList with an already existing instance of Node: p u b l i c L i n k e d L i s t ( Node o ) { = o ; It might also be useful to have a method that can remove all the elements from a list p u b l i c void c l e a r ( ) { = n u l l ;. p.19/74. p.20/74

Linked list implementation (3) Since the attribute is protected, a user of class LinkedList is not able to inspect the value of So, it makes sense to have an accessor for it p u b l i c Node gethead ( ) { r e t u r n ( ) ; An important operation is to check whether a list is empty We could do so using gethead and a comparison operation, but this operation is performed often enough to grant a special method Obviously, a list is empty if is equal to / / Test i f the l i s t i s empty p u b l i c boolean isempty ( ) { r e t u r n ( = = n u l l ) ; To do We still need to implement all operations we have defined on lists: Inserting an element at a specified position into a list Locating the position of a specified element Retrieving an element from a specified position in a list Deleting an element at a specified position in a list Printing all elements in a list. p.21/74. p.22/74 Inserting at the front of a linked list (1) Data Structures and Information Systems Part 1: Data Structures Michele Zito We want to insert an object o at the front of a linked list First, we deal with the case that the list is empty 1. Create a new node storing object o 2. Make the list refer to the new node Lecture 7: List operations. p.23/74. p.24/74

Inserting at the front of a linked list (1) We want to insert an object o at the front of a linked list First, we deal with the case that the list is empty 1. Create a new node storing object o 2. Make the list refer to the new node Inserting at the front of a linked list (1) We want to insert an object o at the front of a linked list First, we deal with the case that the list is empty 1. Create a new node storing object o 2. Make the list refer to the new node o o. p.24/74. p.24/74 Inserting at the front of a linked list (2) We want to insert an object o at the front of a linked list We now deal with the case that the list already contains at least one node 1. Create a new node storing object o 2. Make the link part of the new node refer to what the of the list is referring to 3. Make the list refer to the new node Inserting at the front of a linked list (2) We want to insert an object o at the front of a linked list We now deal with the case that the list already contains at least one node 1. Create a new node storing object o 2. Make the link part of the new node refer to what the of the list is referring to 3. Make the list refer to the new node o. p.25/74. p.25/74

Inserting at the front of a linked list (2) We want to insert an object o at the front of a linked list We now deal with the case that the list already contains at least one node 1. Create a new node storing object o 2. Make the link part of the new node refer to what the of the list is referring to 3. Make the list refer to the new node Inserting at the front of a linked list (2) We want to insert an object o at the front of a linked list We now deal with the case that the list already contains at least one node 1. Create a new node storing object o 2. Make the link part of the new node refer to what the of the list is referring to 3. Make the list refer to the new node o o. p.25/74. p.25/74 Inserting at the front of a linked list (3) The algorithm for inserting an object at the front of a non-empty list also works for an empty list Also, we can merge the first two steps of the algorithm into one Then the following method implements our algorithm: / / I n s e r t an o b j e c t at the f r o n t of a l i n k e d l i s t p u b l i c void a d d F i r s t ( Object o ) { = new Node ( o, ) ; The expression new ListItem(o, ) creates a new node and makes sure that its link part refers to what the of the list is referring to Then, we make the of the list refer to the new node by an assignment Deleting at the front of a linked list (1) We want to delete the first node at the front of a linked list 1. Check whether the linked list is empty; if so, we cannot proceed further and have to give notification that the 2. Since we can now assume that the linked list is non-empty, there is a first element in the linked list; Make the of the list refer to what the link part of this element is referring to. p.26/74. p.27/74

Deleting at the front of a linked list (1) Deleting at the front of a linked list (1) We want to delete the first node at the front of a linked list 1. Check whether the linked list is empty; if so, we cannot proceed further and have to give notification that the 2. Since we can now assume that the linked list is non-empty, there is a first element in the linked list; Make the of the list refer to what the link part of this element is referring to We want to delete the first node at the front of a linked list 1. Check whether the linked list is empty; if so, we cannot proceed further and have to give notification that the 2. Since we can now assume that the linked list is non-empty, there is a first element in the linked list; Make the of the list refer to what the link part of this element is referring to. p.27/74. p.27/74 Deleting at the front of a linked list (2) Traversing a linked list (1) The algorithm for deleting the first node at the front of a linked list also works in the case that the list contains exactly one node Since this operation can fail, we should throw an exception if that happens; instead we give our method a boolean return value, and return false if it fails Then the following method implements our algorithm: So far, all our operations were taking place at the front of a linked list For all other operations we need to be able to traverse a linked list To locate a specified element (retrieval or deletion) To insert an element at a specific position To print out all the elements p u b l i c boolean removefirst ( ) { i f ( isempty ( ) ) / / Empty l i s t nothing to delete r e t u r n f a l s e ; =. getnext ( ) ; r e t u r n t r u e ;. p.28/74. p.29/74

Traversing a linked list (2) As we have no method so far to find out the number of nodes in a linked list, we cannot use a for-loop Also, we do not have a method that, given a number i can give us the ith node of a linked list To traverse a linked list we start from the of the linked list and move on to the item along until is encountered (the end of the list) using a temporary reference Traversing a linked list (2) As we have no method so far to find out the number of nodes in a linked list, we cannot use a for-loop Also, we do not have a method that, given a number i can give us the ith node of a linked list To traverse a linked list we start from the of the linked list and move on to the item along until is encountered (the end of the list) using a temporary reference temp. p.30/74. p.30/74 Traversing a linked list (2) As we have no method so far to find out the number of nodes in a linked list, we cannot use a for-loop Also, we do not have a method that, given a number i can give us the ith node of a linked list To traverse a linked list we start from the of the linked list and move on to the item along until is encountered (the end of the list) using a temporary reference temp Traversing a linked list (2) As we have no method so far to find out the number of nodes in a linked list, we cannot use a for-loop Also, we do not have a method that, given a number i can give us the ith node of a linked list To traverse a linked list we start from the of the linked list and move on to the item along until is encountered (the end of the list) using a temporary reference temp. p.30/74. p.30/74

Traversing a linked list (2) As we have no method so far to find out the number of nodes in a linked list, we cannot use a for-loop Also, we do not have a method that, given a number i can give us the ith node of a linked list To traverse a linked list we start from the of the linked list and move on to the item along until is encountered (the end of the list) using a temporary reference temp String representation of a linked list The application of this algorithm for traversing a linked list will be to construct a string representation of a linked list p u b l i c S t r i n g t o S t r i n g ( ) { / / Declare temporary node and i n i t i a l i s e i t with Node temp = ; / / Declare s t r i n g v a r i a b l e stringrep and / / i n i t i a l i s e i t to the empty s t r i n g S t r i n g stringrep = new S t r i n g ( ) ; while ( temp! = n u l l ) { stringrep + = " " + temp. getdata ( ) ; temp = temp. getnext ( ) ; r e t u r n ( stringrep ) ;. p.30/74. p.31/74 Inserting at the end of a linked list (1) We want to insert an object o at the end of a linked list 1. Create a new node storing object o 2. We use a temporary reference to traverse the linked list until we reach the last node (Keep in mind that the of the linked list might already be the last node ) 3. Make the link part of this current last node refer to the new node Inserting at the end of a linked list (1) We want to insert an object o at the end of a linked list 1. Create a new node storing object o 2. We use a temporary reference to traverse the linked list until we reach the last node (Keep in mind that the of the linked list might already be the last node ) 3. Make the link part of this current last node refer to the new node. p.32/74. p.32/74

Inserting at the end of a linked list (1) We want to insert an object o at the end of a linked list 1. Create a new node storing object o 2. We use a temporary reference to traverse the linked list until we reach the last node (Keep in mind that the of the linked list might already be the last node ) 3. Make the link part of this current last node refer to the new node temp Inserting at the end of a linked list (1) We want to insert an object o at the end of a linked list 1. Create a new node storing object o 2. We use a temporary reference to traverse the linked list until we reach the last node (Keep in mind that the of the linked list might already be the last node ) 3. Make the link part of this current last node refer to the new node temp. p.32/74. p.32/74 Inserting at the end of a linked list (1) We want to insert an object o at the end of a linked list 1. Create a new node storing object o 2. We use a temporary reference to traverse the linked list until we reach the last node (Keep in mind that the of the linked list might already be the last node ) 3. Make the link part of this current last node refer to the new node temp Inserting at the end of a linked list (1) We want to insert an object o at the end of a linked list 1. Create a new node storing object o 2. We use a temporary reference to traverse the linked list until we reach the last node (Keep in mind that the of the linked list might already be the last node ) 3. Make the link part of this current last node refer to the new node temp. p.32/74. p.32/74

Inserting at the end of a linked list (2) The following method addlast implements the algorithm for inserting an object at the end of a linked list Note how it takes care of the special case that is already referring to p u b l i c void addlast ( Object o ) { Node temp = ; Node newnode = new Node ( o, n u l l ) ; i f ( = = n u l l ) = newnode ; else { while ( temp. getnext ( )! = n u l l ) temp = temp. getnext ( ) ; temp. setnext ( newnode ) ;. p.33/74 Inserting in a linked list (3) Since the argument of both addfirst and addlast are of type Object, to insert elements of a primitive type in a linked list we would have to make use of a wrapper class We can again provide special insertion methods for each primitive type, e.g. p u b l i c void a d d F i r s t ( i n t ) { = new Node (new I n t e g e r ( ), ) ; p u b l i c void addlast ( i n t ) { t h i s. addlast (new I n t e g e r ( ) ) ;. p.34/74 Deleting at the end of a linked list (1) We want to delete the last node in a linked list 1. Check whether the linked list is empty; if so, we cannot proceed further and have to give notification that the 2. Traverse the linked list until you reach the last but one node of the list; Make the link part of this node refer to Deleting at the end of a linked list (1) We want to delete the last node in a linked list 1. Check whether the linked list is empty; if so, we cannot proceed further and have to give notification that the 2. Traverse the linked list until you reach the last but one node of the list; Make the link part of this node refer to del temp. p.35/74. p.35/74

Deleting at the end of a linked list (1) We want to delete the last node in a linked list 1. Check whether the linked list is empty; if so, we cannot proceed further and have to give notification that the 2. Traverse the linked list until you reach the last but one node of the list; Make the link part of this node refer to del Deleting at the end of a linked list (1) We want to delete the last node in a linked list 1. Check whether the linked list is empty; if so, we cannot proceed further and have to give notification that the 2. Traverse the linked list until you reach the last but one node of the list; Make the link part of this node refer to del temp temp. p.35/74. p.35/74 Deleting at the end of a linked list (1) We want to delete the last node in a linked list 1. Check whether the linked list is empty; if so, we cannot proceed further and have to give notification that the 2. Traverse the linked list until you reach the last but one node of the list; Make the link part of this node refer to del temp Deleting at the end of a linked list (2) There are two special cases we have to deal with: 1. The linked list is empty: Then we could throw an exception; instead we return the boolean value false 2. The linked list contains exactly one node: Then we make the field of the linked list refer to (and return the boolean value true p u b l i c boolean removelast ( ) { i f ( isempty ( ) ) / / Empty l i s t r e t u r n f a l s e ; else { / / Non empty l i s t Node temp = ; Node del =. getnext ( ) ; i f ( del = = n u l l ) / / Single node l i s t = n u l l ; else {.... p.35/74. p.36/74

Deleting at the end of a linked list (3) The complete code of removelast is as follows: p u b l i c boolean removelast ( ) { i f ( isempty ( ) ) / / Empty l i s t r e t u r n f a l s e ; else { / / Non empty l i s t Node temp = ; Node del =. getnext ( ) ; i f ( del = = n u l l ) / / Single node l i s t = n u l l ; else { / / More than one node while ( del. getnext ( )! = n u l l ) { temp = del ; del = del. getnext ( ) ; temp. setnext ( n u l l ) ; ; r e t u r n t r u e ; / / Successful d e l e t i o n Deleting a given object (1) We can use a similar algorithms if we want to delete a node in a linked list storing a given object o 1. Check whether the linked list is empty; if so, we will not find o in our linked list and have to give notification that the operation has failed 2. Traverse the linked list until you reach the node N storing o, keeping track of the previous node using a temporary reference variable; Make the link part of the previous node refer to the node after N. p.37/74. p.38/74 Deleting a given object (2) Deleting a given object (2) Traverse the linked list until you reach the node N storing o, keeping track of the previous node using a temporary reference variable; Make the link part of the previous node refer to the node after N Traverse the linked list until you reach the node N storing o, keeping track of the previous node using a temporary reference variable; Make the link part of the previous node refer to the node after N del o node D prev o node D. p.39/74. p.39/74

Deleting a given object (2) Deleting a given object (2) Traverse the linked list until you reach the node N storing o, keeping track of the previous node using a temporary reference variable; Make the link part of the previous node refer to the node after N del Traverse the linked list until you reach the node N storing o, keeping track of the previous node using a temporary reference variable; Make the link part of the previous node refer to the node after N del prev o node D prev o node D. p.39/74. p.39/74 Deleting a given object (2) Deleting a given object (2) Traverse the linked list until you reach the node N storing o, keeping track of the previous node using a temporary reference variable; Make the link part of the previous node refer to the node after N del Traverse the linked list until you reach the node N storing o, keeping track of the previous node using a temporary reference variable; Make the link part of the previous node refer to the node after N del prev o node D prev o node D. p.39/74. p.39/74

Deleting a given object (3) Deleting a given object (4) There are two special cases we have to deal with: 1. The linked list is empty: Then we could throw an exception; instead we return the boolean value false 2. The node to delete is the first node of the list: Then we make the field of the linked list refer to second node of the linked list (which may be ) and return the boolean value true p u b l i c boolean remove ( Object o ) { i f ( isempty ( ) ) / / Empty l i s t r e t u r n f a l s e ; else { / / Non empty l i s t Node del = ; Node prev = n u l l ; while (! o. equals ( del. getdata ( ) ) ) { prev = del ; i f ( del. getnext ( ) = = n u l l ) r e t u r n f a l s e ; else del = del. getnext ( ) ; i f ( del = = ) =. getnext ( ) ; / / Delete f i r s t node else prev. setnext ( del. getnext ( ) ) ; r e t u r n t r u e ;. p.40/74. p.41/74 Locating a given object (1) We can easily convert our algorithm for deleting a given object into an algorithm which determines the position of a given object in a linked list We define that the first node in a linked list has position 0, to be more consistent with the notion of an index in an array If the given object is not stored in the linked list, then we return -1 as result Locating a given object (2) p u b l i c i n t p o s i t i o n O f ( Object o ) { i n t pos = 0 ; Node temp = ; while ( temp! = n u l l ) { i f ( o. equals ( temp. getdata ( ) ) ) r e t u r n pos ; temp = temp. getnext ( ) ; pos ++; r e t u r n 1; Note that remove and positionof are not very robust: We should check whether the argument given to these methods is Finally, here is a specialised version of positionof which locates an integer number: p u b l i c i n t p o s i t i o n O f ( i n t number ) { r e t u r n t h i s. p o s i t i o n O f ( new I n t e g e r ( number ) ) ;. p.42/74. p.43/74

Topics Data Structures and Information Systems Part 1: Data Structures Michele Zito Efficiency of Linked Lists Doubly linked lists Deleting at the end of a doubly linked list Lecture 8: Singly and doubly linked lists. p.44/74. p.45/74 Efficiency of (Singly) Linked Lists Space efficiency of (singly) linked lists We know that a well-chosen structure should try to minimise memory usage (avoid the allocation of unnecessary space) a well-chosen structure will include operations that are efficient in terms of speed of execution (based on some well-chosen algorithm) Question: How well does a (Singly) Linked List fare on these criteria, compared to an Array structure storing the same? A linked list stores in nodes where each node has a field storing the a item and a field storing a reference to the node Our operations for inserting and deleting make sure that the number of nodes exactly matches the number of items to be stored So, we never have more nodes than items, but we waste space on the reference stored in each node In comparison, using Arrays, we would simply store the items consecutively starting from position zero. No space is wasted on additional references, but we may have many empty components (at the end) which waste space. p.46/74. p.47/74

Time efficiency (1) Time efficiency (2) For our purposes the most important measure for the speed of execution is number of accesses while performing an operation In an Array inserting/deleting at the front requires moving all elements already in the array in the worst-case a number of accesses related to the length of the array. the longer the list the longer it will take to perform such operation! inserting/deleting at the end requires only the manipulation of the first free component in the array we always need just a constant number of accesses: time required does not depend on the length of the list. p.48/74 For our purposes the most important measure for the speed of execution is number of accesses while performing an operation In a (singly) linked list inserting/deleting at the front requires only accessing and accessing the current first node of the list constant number of accesses time required does not depend on the length of the list inserting/deleting at the end requires traversing the list nodes until we reach the last or last but one node in the worst-case a number of accesses related to the length of the array. the longer the list the longer it will take to perform such operation!. p.49/74 Improving our implementation Considerations (1) Question: How can we improve the performances of these structures? Inserting at the end of a linked list can be improved by adding a reference to the last node in a linked list. p.50/74. p.51/74

Considerations (1) Considerations (1) Inserting at the end of a linked list can be improved by adding a reference to the last node in a linked list node D o Inserting at the end of a linked list can be improved by adding a reference to the last node in a linked list node D o. p.51/74. p.51/74 Considerations (1) Inserting at the end of a linked list can be improved by adding a reference to the last node in a linked list node D o Considerations (2) However, for deleting at the end of a linked list this does not help, since to do that, we need to manipulate the last but one node of the list (not the last node). p.51/74. p.52/74

Doubly linked lists So, to deal with the problem of deleting at the end of a linked list more efficiently, we need to have list nodes that have two references, one to the node and one to the previous node This is advantageous for going forwards and backwards through the list Such a linked list is called a doubly linked list, in contrast to the singly linked list we already know. p.53/74 oubly linked lists: Node implementation ( / / Accessors p u b l i c Object getdata ( ) { r e t u r n ( ) ; p u b l i c i n t g e t I n t D a t a ( ) { r e t u r n ( ( ( I n t e g e r ) ). i n t V a l u e ( ) ) ; p u b l i c DLLNode getnext ( ) { r e t u r n ( ) ; p u b l i c DLLNode getprev ( ) { r e t u r n ( prev ) ; / / Mutators p u b l i c void setdata ( Object o ) { = o ; p u b l i c void s e t I n t D a t a ( i n t number ) { = new I n t e g e r ( number ) ; p u b l i c void setnext ( DLLNode item ) { = item ; p u b l i c void setprev ( DLLNode item ) { prev = item ; Doubly linked lists: Node implementation ( cl a ss DLLNode { protected Object ; / / Data stored i n node protected DLLNode prev ; / / Link to previous node protected DLLNode ; / / Link to node / / Constructors p u b l i c DLLNode ( Object o, DLLNode p, DLLNode n ) { = o ; / / Set prev = p ; / / Set reference t o previous node = n ; / / Set reference t o node p u b l i c DLLNode ( i n t number, DLLNode p, DLLNode n ) { = new I n t e g e r ( number ) ; prev = p ; = n ; / / Accessors and Mutators. p.54/74 Doubly linked lists: Implementation p u b l i c class DLL { protected DLLNode ; / / Reference to f i r s t element protected DLLNode t a i l ; / / Reference to l a s t element / / Constructor creates an empty DLL p u b l i c DLL ( ) { = n u l l ; t a i l = n u l l ; p u b l i c DLLNode gethead ( ) { r e t u r n ( ) ; p u b l i c DLLNode g e t T a i l ( ) { r e t u r n ( t a i l ) ; / / Delete a l l nodes i n a DLL p u b l i c void c l e a r ( ) { = n u l l ; t a i l = n u l l ; / / Check f o r empty DLL p u b l i c boolean isempty ( ) { r e t u r n ( = = n u l l ) ; / / Check f o r DLL with e x a c t l y one node p u b l i c boolean i s S i n g l e t o n ( ) { r e t u r n ( (! = n u l l ) & & ( = = t a i l ) ) ;. p.55/74 / / Other methods. p.56/74

Doubly linked lists: Deleting at the end (1) We want to delete the last node in a doubly linked list 1. Check whether the list is empty; if so, give notification that the 2. Check whether there is exactly one node in the list; if so, make both and refer to 3. Otherwise, make refer to the node.prev is referring to, then make. refer to Doubly linked lists: Deleting at the end (1) We want to delete the last node in a doubly linked list 1. Check whether the list is empty; if so, give notification that the 2. Check whether there is exactly one node in the list; if so, make both and refer to 3. Otherwise, make refer to the node.prev is referring to, then make. refer to. p.57/74. p.57/74 Doubly linked lists: Deleting at the end (1) We want to delete the last node in a doubly linked list 1. Check whether the list is empty; if so, give notification that the 2. Check whether there is exactly one node in the list; if so, make both and refer to 3. Otherwise, make refer to the node.prev is referring to, then make. refer to Doubly linked lists: Deleting at the end (1) We want to delete the last node in a doubly linked list 1. Check whether the list is empty; if so, give notification that the 2. Check whether there is exactly one node in the list; if so, make both and refer to 3. Otherwise, make refer to the node.prev is referring to, then make. refer to. p.57/74. p.57/74

Doubly linked lists: Deleting at the end (2) The code of removelast for a doubly linked list is as follows: p u b l i c boolean removelast ( ) { i f ( isempty ( ) ) / / Empty l i s t r e t u r n f a l s e ; else { i f ( i s S i n g l e t o n ( ) ) / / Singleton l i s t t h i s. c l e a r ( ) ; else { / / L i s t with at l e a s t two nodes t a i l = t a i l. prev ; t a i l. = n u l l ; r e t u r n t r u e ; Doubly linked lists: Inserting at the end (1 We want to insert an object o at the end of a doubly linked list 1. Create a new node N storing object o 2. Make of N refer to and prev of N refer to 3. If the list is currently empty, make and refer to N 4. Otherwise, make the field in the node is referring to, refer to N; then make refer to N. p.58/74. p.59/74 Doubly linked lists: Inserting at the end (1 We want to insert an object o at the end of a doubly linked list 1. Create a new node N storing object o 2. Make of N refer to and prev of N refer to 3. If the list is currently empty, make and refer to N 4. Otherwise, make the field in the node is referring to, refer to N; then make refer to N node N o Doubly linked lists: Inserting at the end (1 We want to insert an object o at the end of a doubly linked list 1. Create a new node N storing object o 2. Make of N refer to and prev of N refer to 3. If the list is currently empty, make and refer to N 4. Otherwise, make the field in the node is referring to, refer to N; then make refer to N node N o. p.59/74. p.59/74

Doubly linked lists: Inserting at the end (1 We want to insert an object o at the end of a doubly linked list 1. Create a new node N storing object o 2. Make of N refer to and prev of N refer to 3. If the list is currently empty, make and refer to N 4. Otherwise, make the field in the node is referring to, refer to N; then make refer to N node N o Doubly linked lists: Inserting at the end (1 We want to insert an object o at the end of a doubly linked list 1. Create a new node N storing object o 2. Make of N refer to and prev of N refer to 3. If the list is currently empty, make and refer to N 4. Otherwise, make the field in the node is referring to, refer to N; then make refer to N node N o. p.59/74. p.59/74 Doubly linked lists: Inserting at the end (2 The code of addlast for a doubly linked list is as follows: p u b l i c void addlast ( Object o ) { DLLNode newnode = new DLLNode ( o, n u l l, n u l l ) ; newnode. setprev ( t a i l ) ; i f ( isempty ( ) ) = newnode ; else t a i l. setnext ( newnode ) ; t a i l = newnode ; Doubly linked lists: Deleting at the front (1 We want to delete the first node in a doubly linked list 1. Check whether the list is empty; if so, give notification that the 2. Check whether there is exactly one node in the list; if so, make both and refer to 3. Otherwise, make refer to the node. is referring to; then make prev in the node is now referring to, refer to. p.60/74. p.61/74

Doubly linked lists: Deleting at the front (1 We want to delete the first node in a doubly linked list 1. Check whether the list is empty; if so, give notification that the 2. Check whether there is exactly one node in the list; if so, make both and refer to 3. Otherwise, make refer to the node. is referring to; then make prev in the node is now referring to, refer to Doubly linked lists: Deleting at the front (1 We want to delete the first node in a doubly linked list 1. Check whether the list is empty; if so, give notification that the 2. Check whether there is exactly one node in the list; if so, make both and refer to 3. Otherwise, make refer to the node. is referring to; then make prev in the node is now referring to, refer to. p.61/74. p.61/74 Doubly linked lists: Deleting at the front (1 We want to delete the first node in a doubly linked list 1. Check whether the list is empty; if so, give notification that the 2. Check whether there is exactly one node in the list; if so, make both and refer to 3. Otherwise, make refer to the node. is referring to; then make prev in the node is now referring to, refer to Doubly linked lists: Deleting at the front (2 The code of removefirst for a doubly linked list is as follows: p u b l i c boolean removefirst ( ) { i f ( isempty ( ) ) / / Empty l i s t r e t u r n f a l s e ; else { i f ( i s S i n g l e t o n ( ) ) / / Singleton l i s t t h i s. c l e a r ( ) ; else { / / L i s t with at l e a s t two nodes =. ;. prev = n u l l ; r e t u r n t r u e ; Note that this code can be obtained from removelast by replacing all occurrences of by and vice versa, replacing all occurrences of by prev and vice versa. p.61/74. p.62/74

Doubly linked lists: Inserting at the front (1 We want to insert an object o at the front of a doubly linked list 1. Create a new node N storing object o 2. Make prev of N refer to and of N refer to 3. If the list is currently empty, make and refer to N 4. Otherwise, make prev in the node is referring to refer to N; then make refer to N Doubly linked lists: Inserting at the front (1 We want to insert an object o at the front of a doubly linked list 1. Create a new node N storing object o 2. Make prev of N refer to and of N refer to 3. If the list is currently empty, make and refer to N 4. Otherwise, make prev in the node is referring to refer to N; then make refer to N node N o. p.63/74. p.63/74 Doubly linked lists: Inserting at the front (1 We want to insert an object o at the front of a doubly linked list 1. Create a new node N storing object o 2. Make prev of N refer to and of N refer to 3. If the list is currently empty, make and refer to N 4. Otherwise, make prev in the node is referring to refer to N; then make refer to N node N o Doubly linked lists: Inserting at the front (1 We want to insert an object o at the front of a doubly linked list 1. Create a new node N storing object o 2. Make prev of N refer to and of N refer to 3. If the list is currently empty, make and refer to N 4. Otherwise, make prev in the node is referring to refer to N; then make refer to N node N o. p.63/74. p.63/74

Doubly linked lists: Inserting at the front (1 We want to insert an object o at the front of a doubly linked list 1. Create a new node N storing object o 2. Make prev of N refer to and of N refer to 3. If the list is currently empty, make and refer to N 4. Otherwise, make prev in the node is referring to refer to N; then make refer to N node N o Doubly linked lists: Inserting at the front (2 We know that the code for addfirst can be obtained from addlast by replacing all occurrences of by and vice versa, replacing all occurrences of by prev and vice versa Then the code of addfirst for a doubly linked list is as follows: p u b l i c void a d d F i r s t ( Object o ) { DLLNode newnode = new DLLNode ( o, n u l l, n u l l ) ; newnode. setnext ( ) ; i f ( isempty ( ) ) t a i l = newnode ; else. setprev ( newnode ) ; = newnode ;. p.63/74. p.64/74 Doubly linked lists: Traversing in reverse A useful side-effect of having references to previous nodes is that we can easily traverse a list starting from its end going to its front Here is a method that constructs a string representation of a doubly linked list enumerating nodes in reverse order: p u b l i c S t r i n g r e v e r s e S t r i n g ( ) { / / Declare temporary node and i n i t i a l i s e i t with t a i l DLLNode temp = t a i l ; / / Declare s t r i n g v a r i a b l e stringrep and / / i n i t i a l i s e i t to the empty s t r i n g S t r i n g stringrep = new S t r i n g ( ) ; while ( temp! = n u l l ) { stringrep + = " " + temp. getdata ( ) ; temp = temp. getprev ( ) ; r e t u r n ( stringrep ) ; Space efficiency A doubly linked list stores in nodes where each node has a field storing the a item and two fields prev and storing a reference to the previous and node, respectively Our operations for inserting and deleting make sure that in our doubly linked list the number of nodes exactly matches the number of items to be stored So, we never have more nodes than items, but we waste space on the prev reference and reference stored in each node. p.65/74. p.66/74

In a doubly linked list: Time efficiency inserting/deleting at the front requires only accessing, possibly, and accessing the first (two) nodes of the list constant number of accesses time required does not depend on the length of the list inserting/deleting at the end requires only accessing, possibly, and accessing the last (two) nodes of the list constant number of accesses time required does not depend on the length of the list printing a doubly linked list requires traversing the doubly linked list accessing all list nodes all elements need to be accessed! (cannot be improved, inherent property of this operation) Doubly linked lists and Java Java contains a class java.util.linkedlist that is an implementation of a (circular) doubly linked list structure This class provides methods like LinkedList() Constructs an empty list void addfirst(object o) Inserts the given element at the beginning of this list void addlast(object o) Appends the given element to the end of this list Object getfirst() Returns the first element in this list Object getlast() Returns the last element in this list and many more. p.67/74. p.68/74 Example: Train departure information We want to develop an alternative implementation of our information system for train departure information at Liverpool Lime Street Station The information is given in form of a table Time Destination Track 9:10 Manchester 6 9:15 Leeds 10 9:20 Nottingham 7 The only kind of query we deal with is When and where does the train to X leave? The implementation should use the doubly linked list structure. p.69/74 Train departure information: The code (1 First, we define a class TDInfo whose instances store the departure information for a single train (that is, one row of our table) We include a constructor for objects of this class plus accessors for the fields, but no mutators p u b l i c class TDInfo { protected S t r i n g time ; protected S t r i n g c i t y ; protected i n t t r a c k ; p u b l i c TDInfo ( S t r i n g Ttime, S t r i n g T c i t y, i n t Ttrack ) { time = Ttime ; c i t y = T c i t y ; t r a c k = Ttrack ; p u b l i c S t r i n g gettime ( ) { r e t u r n ( time ) ; p u b l i c S t r i n g g e t C i t y ( ) { r e t u r n ( c i t y ) ; p u b l i c i n t gettrack ( ) { r e t u r n ( t r a c k ) ;. p.70/74

Train departure information: The code (2 Train departure information: The code (3 Next we define a class TDIDLL containing all the information in our table Since we only deal with one timetable, we don t need any instances of this class, but use a class variable tdi to store the information We use a static init block to create the TDInfo objects for each train and add them to tdi using the addlast method import java. i o. ; cl a ss TDIDLL { s t a t i c f i n a l DLL t d i = new DLL ( ) ; s t a t i c { t d i. addlast ( new TDInfo ( " 9 : 1 0 ", " Manchester ", 6 ) ) ; t d i. addlast ( new TDInfo ( " 9 : 1 5 ", " Leeds ", 1 0 ) ) ; t d i. addlast ( new TDInfo ( " 9 : 2 0 ", " Nottingham ", 7 ) ) ;. p.71/74 Next we add the searchdest method to TDIDLL As a result this method returns an array with two string components p u b l i c s t a t i c S t r i n g [ ] searchdest ( S t r i n g dest ) { S t r i n g [ ] r e s u l t = n u l l ; DLLNode temp = t d i. gethead ( ) ; while ( temp! = n u l l ) { i f ( ( ( TDInfo ) temp. getdata ( ) ). g e t C i t y ( ). equals ( dest ) ) { r e s u l t = new S t r i n g [ 2 ] ; r e s u l t [ 0 ] = ( ( TDInfo ) temp. getdata ( ) ). gettime ( ) ; r e s u l t [ 1 ] = S t r i n g. valueof ( ( ( TDInfo ) temp. getdata ( ) ). gettrack ( ) ) ; r e t u r n r e s u l t ; else temp = temp. getnext ( ) ; r e t u r n r e s u l t ;. p.72/74 Train departure information: The code (4 Finally, here is our main program that asks the user where he wants to go, uses searchdest to find the required information, and prints it out Note that searchdest is a static class method, so it is not applied to an instance but to TDIDLL (or nothing) instead p u b l i c s t a t i c void main ( S t r i n g args [ ] ) throws IOException { InputStreamReader i n p u t = new InputStreamReader ( System. i n ) ; BufferedReader keyboardinput = new BufferedReader ( i n p u t ) ; System. out. p r i n t l n ( " Where do you want to go? " ) ; S t r i n g [ ] i n f o = TDIDLL. searchdest ( keyboardinput. readline ( ) ) ; i f ( i n f o = = n u l l ) System. out. p r i n t l n ( " Sorry, no t r a i n to t h i s d e s t i n a t i o n " ) ; else System. out. p r i n t l n ( i n f o [ 0 ] + " departing at t r a c k " + i n f o [ 1 ] ) ; Train departure information: Script Here are two runs of the program: Information successfully retrieved Where do you want to go? Leeds 9:15 departing at track 10 No information found Where do you want to go? York Sorry, no train to this destination. p.73/74. p.74/74