Linked Lists. Linked List vs Array vs Python List Singly Linked List Bag ADT Revisited Building Linked Lists

Similar documents
Linked Structures Chapter John Wiley & Sons, Data Structures and Algorithms Using Python, by Rance D. Necaise.

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

Queues. Queue ADT Queue Implementation Priority Queues

COMPSCI 105 S Principles of Computer Science. 17 Linked List(1)

Binary Search Tree. Revised based on textbook author s notes.

Outline. LList: A Linked Implementation of a List ADT Iterators Links vs. Arrays In-class work. 1 Chapter 4: Linked Structures and Iterators

Computer Science Fundamentals 107

CSI33 Data Structures

Algorithms in Systems Engineering ISE 172. Lecture 5. Dr. Ted Ralphs

Chapter 17: Linked Lists

Advanced Sorting. Merge Sort Quick Sort Radix Sort

Agenda & Reading. COMPSCI 105 SS 2015 Principles of Computer Science

CS350: Data Structures Linked Lists

CMPT 225. Lecture 6 linked list

Abstract Data Types Chapter 1


CS 234. Module 3. September 29, CS 234 Module 3 Data structures, ADTs with no order of any kind, Python review 1 / 19

Chapter 17: Linked Lists

What is an algorithm?

Queues The Queue ADT. The Queue ADT is defined by the following operations: init Initialize a new empty queue.

Solution: The examples of stack application are reverse a string, post fix evaluation, infix to postfix conversion.

Walk through previous lectures

CS 331 Midterm Exam 2

Ashish Gupta, Data JUET, Guna

About the Final. Saturday, 7-10pm in Science Center 101. Closed book, closed notes. Not on the final: graphics, file I/O, vim, unix

CSE 230 Intermediate Programming in C and C++

CS 331 Fall 2017 Midterm Exam 2

CSI33 Data Structures

Linked Lists. Linked list: a collection of items (nodes) containing two components: Data Address (link) of the next node in the list

Linked Lists. Linked list: a collection of items (nodes) containing two components: Data Address (link) of the next node in the list

Abstract Data Types. CS 234, Fall Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples

Linked lists. A linked list is considered a recursive data structure because it has a recursive definition.

LINKED IMPLEMENTATION OF LIST

CSE 143. Lecture 7: Linked List Basics reading: 16.2

General Insert Operation

CS 331 Summer 2017 Final Exam

Lecture Notes CPSC 122 (Fall 2014) Today Quiz 7 Doubly Linked Lists (Unsorted) List ADT Assignments Program 8 and Reading 6 out S.

CS532: Design and Analysis of Algorithms. Overview. Linked Lists. Data Structures Intro. Classes, Objects, and Pointers.

Data Structures I: Linked Lists

BBM 201 DATA STRUCTURES

Linked List. ape hen dog cat fox. tail. head. count 5

CS 234. Module 3. September 19, CS 234 Module 3 Data structures, ADTs with no order of any kind, Python review 1 / 33

CSC148: Week 4

Stack. Stack theory. Stack exercises. Algolab (index.html#chapters) Out[1]: Chapter 2.2: Data Structures - Stacks and.

03/31/03 Lab 7. Linked Lists

Priority Queue ADT. Revised based on textbook author s notes.

CS350: Data Structures. Doubly Linked Lists

CS32 Discussion Week 3

Binary Tree Application Expression Tree. Revised based on textbook author s notes.

Programming. Lists, Stacks, Queues

DATA STRUCTURES AND ALGORITHMS

Recursive Objects. Singly Linked List (Part 2)

CS 331 Midterm Exam 2

Linked Lists. Gaddis Ch. 17. CS 2308 :: Spring 2016 Molly O'Neil

Last name... First name... Q1: / 5 Q2: / 6 Q3: / 9

CS 331/401 Summer 2018 Midterm Exam

Data Structures CSCI C343, Fall 2014

CSC148-Section:L0301/L0401

Short Python function/method descriptions:

Announcements. Lab 11 is due tomorrow. Quiz 6 is on Monday. Ninja session tonight, 7-9pm. The final is in two weeks!

A collision is said to occur when two or more keys hash to the same index location.

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

16. Dynamic Data Structures

Short Python function/method descriptions:

n 1 i = n + i = n + f(n 1)

Data Structures & Algorithms

Programming II (CS300)

Chapter 10 Linked Lists A

CSCA48 Term Test 1 Seminar

Sets and Maps. Set Commands Set ADT Set ADT implementation Map ADT Map ADT implementation

Linked lists * Nguyen Viet Ha, Truong Ninh Thuan, Vu Quang Dung Linked lists

List ADT. B/W Confirming Pages

Insertion Sort: an algorithm for sorting an array

Programming II (CS300)

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

! A data structure representing a list. ! A series of dynamically allocated nodes. ! A separate pointer (the head) points to the first

Data Structures and Algorithms

Advanced Programming. Lists. A list is a data structure based on usage of pointers and dynamic allocation of memory.

Outline. The Python Memory Model A Linked Implementation of Lists In-Class Work. 1 Chapter 4: Linked Structures and Iterators

Outline. An Application: A Binary Search Tree. 1 Chapter 7: Trees. favicon. CSI33 Data Structures

FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- MARCH, 2012 DATA STRUCTURE (Common to CT and IF) [Time: 3 hours

Last time s big ideas

CIS 110 Spring 2013 Final Exam, 29 April 2013, Answer Key. Miscellaneous

Lecture 12 ADTs and Stacks

CS200: Queues. Prichard Ch. 8. CS200 - Queues 1

Name: UTLN: CS login: Comp 15 Data Structures Midterm 2018 Summer

Linked List using a Sentinel

! A data structure representing a list. ! A series of nodes chained together in sequence. ! A separate pointer (the head) points to the first

Heaps. Heaps Priority Queue Revisit HeapSort

The combination of pointers, structs, and dynamic memory allocation allow for creation of data structures

Linked Lists and Abstract Data Structures A brief comparison

DNHI Homework 3 Solutions List, Stacs and Queues

Linked Lists. Chapter 4

Data structure and algorithm in Python

Basic Data Structures (Version 7) Name:

CS 61B Data Structures and Programming Methodology. June David Sun

Linked Lists. College of Computing & Information Technology King Abdulaziz University. CPCS-204 Data Structures I

Data Structures. Alice E. Fischer. Lecture 4, Fall Alice E. Fischer Data Structures L4... 1/19 Lecture 4, Fall / 19

! A data type for which: ! An ADT may be implemented using various. ! Examples:

What is a List? elements, with a linear relationship. first) has a unique predecessor, and. unique successor.

Transcription:

Linked Lists Linked List vs Array vs Python List Singly Linked List Bag ADT Revisited Building Linked Lists

Review Arrays Basic sequence container Provides easy and direct element access. Supported at the hardware level. Limited functionality. Fixed size.

Review Python list Extends array functionality. Provides a larger set of operations. Can automatically adjust size as needed. Change in size requires allocation of new array. Insertions and deletions require items to be shifted.

Introduction In this chapter, we introduce the linked list data structure. Can be used to store a collection in linear order. Improves on the construction and management of an array and list. Requires smaller memory allocations. No element shifts for insertions and deletions. Eliminates constant time direct element access.

Step 1: Store the Data create a class, Node, to store the data class Node: def init (self, data): self.data = data create 3 objects: Node(4), Node(1), Node(7) also create 3 variables: a, b, c a = Node(4) b = Node(1) c = Node(7) a b c 4 1 7

Step1: Store the Data class Node: def init (self, data): self.data = data a When I do the command a = Node(4) I create the following object... 4 a is an alias, or another name for Node(4) a.data and Node(4).data both refer to... 4

Step 2: Add a Second Attribute Next add a second attribute to the Node class, called next set its value to None class Node: def init (self, data): self.data = data self.next = None a b c a = Node(4) b = Node(1) c = Node(7) 4 1 7

Step 2: Add a Second Attribute Next Rather than have the variables a, b, and c to refer to the objects have the objects point to each other a.next = b b.next = c a.next is now an alias or refers to the same object that b does a b c 4 1 7

Step 2: Add a Second Attribute Next We can now get rid of variables b and c, because we no longer need them Refer to the next object in the list using the next attribute, i.e. use a.next instead of b Now you no longer have one variable for each data item in the list. a 4 1 7

Node Definition The nodes are constructed from a simple storage class: class ListNode: def init ( self, data ): self.data = data self.next = None

Linked Structure Constructed using a collection of objects called nodes. Each node contains data and at least one reference or link to another node. Linked list a linked structure in which the nodes are linked together in linear order.

Linked List Terms: head first node in the list. tail last node in the list; link field has a null reference.

Linked List Most nodes have no name; they are referenced via the link of the preceding node. head reference the first node must be named or referenced by an external variable. Provides an entry point into the linked list. An empty list is indicated by a null head reference.

Linked List Many different configurations are possible:

Singly Linked List A linked list in which each node contains a single link field and allows for a complete linear order traversal from front to back. Several common operations can be performed.

Traversing the Nodes We can traverse the nodes using a temporary external reference variable. Initialize a temporary reference to the head node. Visit the node.

Traversing the Nodes Advance the temporary reference to the next node using the link field and visit that node.

Traversing the Nodes Repeat the process until the reference falls off the end of the list.

Traversing the Nodes Repeat the process until the reference falls off the end of the list.

Traversal Code Given the head reference, we can traverse the nodes. def traversal( head ): curnode = head while curnode is not None : print( curnode.data ) curnode = curnode.next

Searching We can perform a linear search to determine if the list contains a specific data item. def unorderedsearch( head, target ): curnode = head while curnode is not None and curnode.data!= target : curnode= curnode.next return curnode is not None

Prepending Nodes When working with an unsorted linked list, new values can be inserted at any point. We can prepend new items with little effort. Example: add value 96 to the sample list.

Prepending Nodes Create a new node for the new item. Connect the new node to the list.

Prepending Nodes The resulting list. Python code # Given the head reference and the new item. newnode = ListNode( newitem ) newnode.next = head head = newnode

Removing Nodes An item can be removed from a linked list by removing or unlinking the node containing the item. Find the node containing the item. Unlink it from the list.

Removing Nodes Removing a node from the middle of the list requires a second external reference. Resulting list.

Removing Nodes Removing the first node is a special case. The head reference must be reposition to reference the next node in the list.

Removing Nodes Given the head reference, we can remove a target from a linked list. prednode = None curnode = head while curnode is not None and curnode.data!= target : prednode = curnode curnode = curnode.next if curnode is not None : if curnode is head : head = curnode.next else : prednode.next = curnode.next

The Bag ADT Revisited We can implement the Bag ADT using a linked list. The items will be prepended to the list. Must keep track of the size of the list.

Bag ADT Linked List llistbag.py class Bag : def init ( self ): self._head = None self._size = 0 def len ( self ): return self._size def iter ( self ): return _BagIterator( self._head ) #... # Defines a private storage class for creating list nodes. class _BagListNode( object ): def init ( self, item ) : self.item = item self.next = None

Bag ADT Linked List llistbag.py class Bag: #... def contains ( self, target ): curnode = self._head while curnode is not None and curnode.item!= target : curnode = curnode.next return curnode is not None def add( self, item ): newnode = _BagListNode( item ) newnode.next = self._head self._head = newnode self._size += 1

Bag ADT Linked List llistbag.py class Bag: #... def remove( self, item ): prednode = None curnode = self._head while curnode is not None and curnode.item!= item : prednode = curnode curnode = curnode.next # The item has to be in the bag to remove it. assert curnode is not None, "The item must be in the bag." # Unlink the node and return the item. self._size -= 1 if curnode is self._head : self._head = curnode.next else : prednode.next = curnode.next return curnode.item

Comparing Implementations Operation Python List Linked List b = Bag() O(1) O(1) n = len(b) O(1) O(1) x in b O(n) O(n) b.add(x) O(n) O(1) b.remove(x) O(n) O(n) traversal O(n) O(n)

Building Linked Lists There are more ways to build a linked list than simply prepending nodes to the front. Appending nodes Sorted linked lists

Using a Tail Reference Some applications require items be appended to the end of the linked list. tail reference a second external reference indicating the tail or last node in the list.

Appending Nodes Must manage the tail reference as nodes are added/removed. Example: append 21 to the list.

Appending Nodes Given the head and tail reference, we can add an item to a linked list. newnode = ListNode( item ) if head is None : head = newnode else : tail.next = newnode tail = newnode What is the time complexity to append a node to a linked list, if no tail reference is used?

Removing Nodes If the tail node is removed, the tail reference has to be adjusted.

Removing Nodes Given the head and tail reference, we can remove a node from a linked list. prednode = None curnode = head while curnode is not None and curnode.data!= target : prednode = curnode curnode = curnode.next if curnode is not None : if curnode is head : head = curnode.next else : prednode.next = curnode.next if curnode is tail : tail = prednode

The Sorted Linked List The items in a linked list can be maintained in sorted order.

Sorted List: Searching Searching a sorted list is similar to that of an unsorted list. def sortedsearch( head, target ): curnode = head # Stop early when a larger value is encountered. while curnode is not None and \ curnode.data < target : if curnode.data == target : return True else : curnode = node.next return False

Sorted List: Insert Adding a new node to a sorted list requires locating the correct position within the list. Locating the position is similar to the removal operation. Use a second temporary reference for the predecessor. There are 3 possible cases. front middle back

Sorted List: Insert (1) Insert at the front.

Sorted List: Insert (2) Insert in the middle.

Sorted List: Insert (3) Insert at the end.