CSCI 3333 Data Structures Linked Lists

Slides:



Advertisements
Similar presentations
Chapter 17 Linked Lists.
Advertisements

DATA STRUCTURES USING C++ Chapter 5
CSE Lecture 12 – Linked Lists …
1 Chapter 24 Lists Stacks and Queues. 2 Objectives F To design list with interface and abstract class (§24.2). F To design and implement a dynamic list.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 17: Linked Lists.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 17 Linked.
Starting Out with C++, 3 rd Edition 1 Chapter 17 Linked Lists.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
Queues by Dr. Bun Yue Professor of Computer Science CSCI 3333 Data Structures.
1 Linked-list, stack and queue. 2 Outline Abstract Data Type (ADT)‏ Linked list Stack Queue.
Iterator for linked-list traversal, Template & STL COMP171 Fall 2005.
Lists Chapter 8. 2 Linked Lists As an ADT, a list is –finite sequence (possibly empty) of elements Operations commonly include: ConstructionAllocate &
Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 17: Linked Lists.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
Copyright © 2012 Pearson Education, Inc. Chapter 17: Linked Lists.
© 2006 Pearson Addison-Wesley. All rights reserved5 B-1 Chapter 5 (continued) Linked Lists.
List Interface and Linked List Mrs. Furman March 25, 2010.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
List Structures What is a list? A homogeneous collection of elements with a linear relationship between the elements linear relationship - each element.
Copyright © 2012 Pearson Education, Inc. Chapter 17: Linked Lists.
1 Chapter 24 Implementing Lists, Stacks, Queues, and Priority Queues Jung Soo (Sue) Lim Cal State LA.
Standard Template Library
Lecture 6 of Computer Science II
Cpt S 122 – Data Structures Abstract Data Types
Pointers and Linked Lists
Data Structure By Amee Trivedi.
Pointers and Linked Lists
Vectors 5/31/2018 9:25 AM Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and.
CSCI 3333 Data Structures Stacks.
Sorted Linked List Same objective as a linked list, but it should be sorted Sorting can be custom according to the type of nodes Offers speedups over non-sorted.
Linked Lists Chapter 5 (continued)
Linked Lists Chapter 6 Section 6.4 – 6.6
Lists CS 3358.
List ADT & Linked Lists.
CSE 143 Linked Lists [Chapter , 8.8] 3/30/98.
Standard Template Library (STL)
Chapter 4 Linked Lists.
Programming Abstractions
A Doubly Linked List There’s the need to access a list in reverse order prev next data dnode header 1.
CSCI 3333 Data Structures Linked Lists.
Chapter 4 Linked Lists
Data Structures and Algorithms IT12112
Prof. Neary Adapted from slides by Dr. Katherine Gibson
Introduction to Linked Lists
Chapter 16-2 Linked Structures
Linked Lists.
Object Oriented Programming COP3330 / CGS5409
Chapter 4 Linked Lists.
Chapter 18: Linked Lists.
Programming in Java Lecture 11: ArrayList
Linked List (Part I) Data structure.
Chapter 3 Lists, Stacks, and Queues Abstract Data Types, Vectors
Programming Abstractions
Programming II (CS300) Chapter 07: Linked Lists and Iterators
Chapter 24 Implementing Lists, Stacks, Queues, and Priority Queues
Doubly Linked List Implementation
Recursive Linked List Operations
Chapter 4 Linked Lists.
Chapter 17: Linked Lists.
Chapter 16 Linked Structures
Computer Science and Engineering
ArrayLists 22-Feb-19.
Collections Framework
Linked Lists Chapter 5 (continued)
Part of the Collections Framework
Doubly Linked List Implementation
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
Linked Lists Chapter 5 (continued)
Sequences 08/30/17 08/30/17 Unit III. Linked Lists 1.
Data Structures & Programming
Presentation transcript:

CSCI 3333 Data Structures Linked Lists by Dr. Bun Yue Professor of Computer Science yue@uhcl.edu http://sce.uhcl.edu/yue/ 2013

Acknowledgement Mr. Charles Moen Dr. Wei Ding Ms. Krishani Abeysekera Dr. Michael Goodrich

Static Data Structures The size of static data structures do not change. Example: array. During runtime, if there are more elements to be stored in an array: A new array needs to be created. The old array may be deleted. Elements are copied. Expensive!

Dynamic Data Structures The size of a dynamic data structure can change during runtime. Many applications need to use dynamic data structures.

Linked List ADT A linked list is a sequence of nodes linked in a chain. Some operations: Create Delete Traverse Insert a node Delete a node Insert a linked list Delete a linked list …

Linked Lists vs. Arrays Advantages: Disadvantages: Dynamic: size changes on demand. Insertion and deletion of nodes: can be faster in some situations. Disadvantages: May not be randomly accessible efficiently. Options: Programmers needs to manage memory. Automatic garbage collection may bring performance issues.

Linked List ADT There are many kinds of linked lists implemented by different languages. They are different ADTs. We can study the ADTs to use them without knowing how they are implemented.

Example: C++ STL list Some methods: begin: returns an iterator addressing the first element in a list. pop_back:deletes the element at the end of a list. pop_front: deletes the element at the beginning of a list. push_back: adds an element to the end of a list. push_front: adds an element to the beginning of a list. … assign Erases elements from a list and copies a new set of elements to the target list. back Returns a reference to the last element of a list. begin Returns an iterator addressing the first element in a list. clear Erases all the elements of a list. empty Tests if a list is empty. end Returns an iterator that addresses the location succeeding the last element in a list. erase Removes an element or a range of elements in a list from specified positions. front Returns a reference to the first element in a list. get_allocator Returns a copy of the allocator object used to construct a list. insert Inserts an element or a number of elements or a range of elements into a list at a specified position. max_size Returns the maximum length of a list. merge Removes the elements from the argument list, inserts them into the target list, and orders the new, combined set of elements in ascending order or in some other specified order. pop_back Deletes the element at the end of a list. pop_front Deletes the element at the beginning of a list. push_back Adds an element to the end of a list. push_front Adds an element to the beginning of a list. rbegin Returns an iterator addressing the first element in a reversed list. remove Erases elements in a list that match a specified value. remove_if Erases elements from the list for which a specified predicate is satisfied. rend Returns an iterator that addresses the location succeeding the last element in a reversed list. resize Specifies a new size for a list. reverse Reverses the order in which the elements occur in a list. size Returns the number of elements in a list. sort Arranges the elements of a list in ascending order or with respect to some other order relation. splice Removes elements from the argument list and inserts them into the target list. swap Exchanges the elements of two lists. unique Removes adjacent duplicate elements or adjacent elements that satisfy some other binary predicate from the list.

Example Program #include <list> #include <iostream> using namespace std ; typedef list<int> INT_LIST; int main() { INT_LIST ilist; ilist.push_back(1); ilist.push_front(2); ilist.push_front(3); ilist.push_front(4); ilist.push_back(5); cout << ilist.front() << endl; cout << ilist.back() << endl;

Example Program (cont) INT_LIST::iterator i; cout << "Int list content:"; for (i = ilist.begin(); i != ilist.end(); ++i) cout << " " << *i; // Note * cout << endl; (*i)++; ilist.pop_front(); ilist.pop_back(); }

Output 1 ilist.push_back(1); ilist.push_front(2); ilist.push_front(3); cout << ilist.front() << endl; cout << ilist.back() << endl; Output: 4 5

Output 2 INT_LIST::iterator i; cout << "Int list content:"; for (i = ilist.begin(); i != ilist.end(); ++i) cout << " " << *i; // Note * cout << endl; (*i)++; Output: Int list content: 4 3 2 1 5 Int list content: 5 4 3 2 6

Output 3 ilist.pop_front(); ilist.pop_back(); cout << "Int list content:"; for (i = ilist.begin(); i != ilist.end(); ++i) cout << " " << *i; cout << endl; Output: Int list content: 4 3 2

Perl Example In Perl, an array is also a list. It is built into the language. (You can see the importance of lists here.) Array/List variables start with the symbol @, e.g. @a. List elements are scalar (which starts with the symbol $), e.g. $a[1], $a[12], etc.

Perl’s List Examples @num[1,2] = (3,4); # $num[1] = 3; $num[2] = 4; # swap $num[1] and $num[2]; @num[1,2] = @num[3,3]; # $num[1] = $num[3]; $num[2] = $num[3]; ($num[1], $num[2]) = ($num[2], $num[1]); # swap $num[1] and $num[2]; @num = (1,2,3,4,5)[3,2,1]; # @num = (4,3,2); ($first, @num) = @num; # remove the first element of @num into $first (@num, $last) = @num; # pop the last element to $last

Java’s List Interface ADT Java has a List interface for ordered collection (sequence). Super-interface: Collection Iterable Some known implementation classes: AbstractList LinkedList ArrayList Vector … Practical APIs are much richer than those found in some textbooks!

Interable Interface Target of a for each statement. One method only Iterator<T>iterator(): returns an iterator over a set of elements of type T. Iterator<T> interface’s methods: hasNext() next() remove()

Collection Interface Group of objects, possibly with duplicates. Super-interface: iterable. Some methods: add(E e) addAll(Collection<? extends E> c) contains(Object o) remove(Object o) removeAll(Collection<?> c) size() toArray() … booleanadd(E e)           Ensures that this collection contains the specified element (optional operation). booleanaddAll(Collection<? extends E> c)           Adds all of the elements in the specified collection to this collection (optional operation). voidclear()           Removes all of the elements from this collection (optional operation). booleancontains(Object o)           Returns true if this collection contains the specified element. booleancontainsAll(Collection<?> c)           Returns true if this collection contains all of the elements in the specified collection. booleanequals(Object o)           Compares the specified object with this collection for equality. inthashCode()           Returns the hash code value for this collection. booleanisEmpty()           Returns true if this collection contains no elements. Iterator<E>iterator()           Returns an iterator over the elements in this collection. booleanremove(Object o)           Removes a single instance of the specified element from this collection, if it is present (optional operation). booleanremoveAll(Collection<?> c)           Removes all of this collection's elements that are also contained in the specified collection (optional operation). booleanretainAll(Collection<?> c)           Retains only the elements in this collection that are contained in the specified collection (optional operation). intsize()           Returns the number of elements in this collection. Object[]toArray()           Returns an array containing all of the elements in this collection.<T> T[]toArray(T[] a)           Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array.

List Interface New required methods added: Random access: Searching: E get(int index) E remove(int index) Searching: int indexOf(Object o) int lastIndexOf(Object o) List Iterator: ListIterator<E> listIterator()

Concrete Class LinkedList<E> Interface implemented: Serializable Cloneable Iterable<E> Collection<E>  Queue<E>  Deque<E> Iterable<E>  Collection<E>  List<E> <E>: Actual E should be a class (not int, float, etc)

LinkedList Methods From implementing Dequeue: void addFirst(E e) void addLast(E e) E removeFirst() E removeLast() E offerFirst(): retrieve, not remove, exception version for empty Dequeue. E peekFirst(): retrieve, not remove, return null version for empty Dequeue. …

LinkedList Methods From implementing List: add(E e) E get(int index) E remove(int index) remove(Object o) int indexOf(Object o)

Finding the Right Structures APIs are usually feature rich. Study purposes of classes and interfaces. Study hierarchical class and interface structures. Study methods available.

Examples Good to critically read program code. http://www.java-samples.com/showtutorial.php?tutorialid=347 http://www.idevelopment.info/data/Programming/java/collections/LinkedListExample.java

Implementation Issues You do not need to know how classes are implemented to use them! However, knowing the implementations: May deepen understanding of the classes for better usages. May help selecting the best class for the application. May transfer this knowledge when you need to implement custom-designed classes yourself.

Example Implementation in C++ Singly linked list of float Each node has only one pointer to its successor. The list stores a head pointer to the head of the list. If the list is empty, the head pointer is null. For simplicity, each node stores an float.

Implementation issues Data members: Value of float head pointer tail pointer: for efficiency size of the list: for efficiency. Tips: ensure all data members properly updated in operations.

Node class FloatList{ private: // Declare a structure for the list. // Simliar to nested classes in Java struct ListNode { float value; struct ListNode *next; }; ListNode *head, *tail; // head and tail pointers int _size;

Method Prototypes public: FloatList() // Constructor { head = tail = NULL; _size = 0; } ~FloatList(); // Destructor Tips: always include constructors and destructors.

Method Prototypes void appendTailNode(float); // insert node at the tail. bool deleteHeadNode(); // delete node at the head. bool deleteNode(float); // delete the first occurrence of the float // list. void displayList(); int size() { return _size; } bool isEmpty() { return _size == 0; } };

Method Implementations void FloatList::appendTailNode(float num) { ListNode *newNode; // Allocate a new node & store num newNode = new ListNode; newNode->value = num; newNode->next = NULL; if (head==NULL) { // empty list head = tail = newNode; } else { tail->next = newNode; tail = tail-> next; _size++;

Discussion Maintenance of data members. Trade off of using _size and tail: faster for some operations and slower for others. Definition of newNode as class instead of struct: use of constructors.

deleteHeadNode bool FloatList::deleteHeadNode() { if (head == NULL) return false; else { ListNode *temp = head; head = head-> next; if (head == NULL) tail = NULL; delete temp; _size--; return true; }

Discussion Other possible methods: May change prototype: deleteTailNode May change prototype:

deleteNode(float f) bool FloatList::deleteNode(float f) { if (head == NULL) return false; else { ListNode *curr = head; ListNode *prev = NULL; while (curr != NULL && curr->value != f) { prev = curr; curr = curr-> next; } if (curr == NULL) // do not find the number to be deleted. else // to be continued.

else part { if (prev == NULL) { // the head node contains the number. head = curr-> next; } if (curr == tail) { // the tail node will be deleted. tail = prev; // link the prev node to skip the curr node. prev->next = curr->next; delete curr; _size--; return true;

Discussion Other possible methods. deleteLastNode.

displayList void FloatList::displayList() { ListNode *nodePtr; nodePtr = head; while (nodePtr) cout << nodePtr->value << " "; nodePtr = nodePtr->next; } cout << endl;

Discussion Not flexible. Need an ‘iterator’.

Destructor FloatList::~FloatList(){ ListNode *curr, *next; curr = head; while (curr != NULL) { next = curr->next; delete curr; curr = next; }

Test Program FloatList list; list.appendTailNode(2.2); list.displayList(); cout << "size: " << list.size() << endl; Output: 2.2 3.4 2.2 1.8 2.2 size: 5

Test Program list.deleteHeadNode(); list.displayList(); cout << "size: " << list.size() << endl; list.deleteNode(2.2); Outpit: 3.4 2.2 1.8 2.2 size: 4 3.4 1.8 2.2 size: 3 3.4 1.8 size: 2

Test Program list.deleteHeadNode(); list.displayList(); cout << "size: " << list.size() << endl; Output: size: 0

Discussion Other possible methods: getHeadNodeValue() getTailNodeValue() deleteTailNode() …

Discussion Some operations, deleteTailNode may take longer time, O(N), where N is the number of nodes in the list. May use a doubly linked list. Need to have a way to analyze performance. List only works for float May use template.

Questions and Comments?