COMP 53 – Week Eight Linked Lists.

Slides:



Advertisements
Similar presentations
Linked Lists Geletaw S..
Advertisements

Copyright © 2003 Pearson Education, Inc. Slide 1.
Chapter 17 Linked Data Structures. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives Nodes and Linked Lists Creating,
DATA STRUCTURES USING C++ Chapter 5
Linked List 1. Introduction to Linked List 2. Node Class 3. Linked List 4. The Bag Class with Linked List.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and 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.
2 Preliminaries Options for implementing an ADT List Array has a fixed size Data must be shifted during insertions and deletions Linked list is able to.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Custom Templatized Data Structures.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 4: Linked Lists Data Abstraction & Problem Solving with.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.
1 CSC 222: Computer Programming II Spring 2004 Pointers and linked lists  human chain analogy  linked lists: adding/deleting/traversing nodes  Node.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 17: Linked Lists.
1 Chapter 16 Linked Structures Dale/Weems. 2 Chapter 16 Topics l Meaning of a Linked List l Meaning of a Dynamic Linked List l Traversal, Insertion and.
Slide 1 Linked Data Structures. Slide 2 Learning Objectives  Nodes and Linked Lists  Creating, searching  Linked List Applications  Stacks, queues.
Lists Chapter 8. 2 Linked Lists As an ADT, a list is –finite sequence (possibly empty) of elements Operations commonly include: ConstructionAllocate &
Copyright © 2002 Pearson Education, Inc. Slide 1.
CS162 - Topic #7 Lecture: Dynamic Data Structures –Review of pointers and the new operator –Introduction to Linked Lists –Begin walking thru examples of.
 Memory from the heap  Dynamic memory allocation using the new operator  Build a dynamic linked list  Another way of traversing a linked list 
1 Linked List. Outline Introduction Insertion Description Deletion Description Basic Node Implementation Conclusion.
Linked Lists Data Structures and Algorithms CS 244 Brent M. Dingle, Ph.D. Department of Mathematics, Statistics, and Computer Science University of Wisconsin.
Memory Management.
C++ Programming:. Program Design Including
Pointers and Linked Lists
COMP 53 – Week Fourteen Trees.
Dynamic Allocation Review Structure and list processing
Pointers and Linked Lists
Copy Constructor / Destructors Stacks and Queues
Introduction to Linked Lists
Lectures linked lists Chapter 6 of textbook
Linked Lists Chapter 6 Section 6.4 – 6.6
COMP 53 – Week Eleven Hashtables.
What’s New? Six homework programming assignments. New: five
Exercise 1 From Lec80b-Ponter.ppt.
CSE 143 Linked Lists [Chapter , 8.8] 3/30/98.
Chapter 4 Linked Lists.
classes and objects review
Programming Abstractions
Lists.
Chapter 4 Linked Lists
Sequences 9/18/ :20 PM C201: Linked List.
Linked Data Structures
LinkedList Class.
This pointer, Dynamic memory allocation, Constructors and Destructor
The Bag and Sequence Classes with Linked Lists
Programmazione I a.a. 2017/2018.
Map interface Empty() - return true if the map is empty; else return false Size() - return the number of elements in the map Find(key) - if there is an.
Stack Lesson xx   This module shows you the basic elements of a type of linked list called a stack.
Prof. Neary Adapted from slides by Dr. Katherine Gibson
Lists.
Chapter 16-2 Linked Structures
Linked Lists.
Chapter 4 Linked Lists.
Arrays and Linked Lists
Chapter 18: Linked Lists.
Popping Items Off a Stack Lesson xx
Pointers and Linked Lists
Chapter 17: Linked Lists Starting Out with C++ Early Objects
Programming Abstractions
Chapter 4 Linked Lists.
Chapter 17: Linked Lists.
Chapter 16 Linked Structures
Introduction to C++ Linear Linked Lists
Pointers & Dynamic Data Structures
Linked Lists.
Lists.
Data Structures & Algorithms
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
Data Structures & Programming
Presentation transcript:

COMP 53 – Week Eight Linked Lists

Topics Review Lab 6 Linked List Concepts Creating and Managing Lists Doubly Linked Lists

Why Do We Care More Flexible way to manage data Can grow and shrink based on actual data being used Can handle complex user defined data

By the way, the name of this class!!! Data Structures By the way, the name of this class!!! Data Structures Linear Direct Access Array Hashtable Sequential Access List Stack Queue Nonlinear Hierarchical Tree Heap

Introduction Linked list Pointers are the backbone of lists Constructed using pointers Grows and shrinks during run-time Doubly Linked List : A variation with pointers in both directions Pointers are the backbone of lists Use dynamic variables Different from Arrays in that memory is not in one block Standard Template Library Has predefined versions of some structures

Pointer Review int x = 10; int y = x; int* a = &x; int* b = a; int* c = &y; 5A111110 5A11111C 5A111127 5A111111 5A11111D 5A111128 10 5A111112 5A111129 y 5A11112A 5A111113 5A11111F 5A111114 5A11111F 5A11111E c 10 5A111120 5A11112C x 5A111121 5A111115 a 5A111116 5A111122 5A11112E 5A111117 5A111118 5A111123 5A11112F 5A111115 Pointers are typed. Ex., double* ptr; int *p1, *p2; 5A111119 5A111124 b 5A11111A 5A111125 5A111131 5A11111B 5A111126 5A111132

Pointers  Vars  Pointers &x: “address of x” x is a regular var. &x is a pointer *p: “what p points at” or “contents of p” p is a pointer *p is a regular var.

Nodes are the Lego Blocks Each "node" is variable of struct or class type that’s dynamically created with new Member variables represent data about what list is for: Names, addresses, etc Manufacturing items, inventory counts, costs, etc Student test scores, ranking, etc Nodes also contain pointers to other nodes Provide "links"

Nodes Get Linked Together

Access and Loops are easier with arrays Arrays vs Linked List 7 8 11 14 17 22 [0] [1] [2] [3] [4] [5] Access and Loops are easier with arrays 7 8 11 14 17 22

Arrays vs Linked List Insert Operation 7 8 11 14 17 [0] [1] [2] [3] [4] [5] 10 7 8 11 14 17

Arrays vs Linked List Insert Operation 7 8 11 14 17 [0] [1] [2] [3] [4] [5] 10 10 7 8 11 14 17

Arrays vs Linked List Delete Operation 7 8 11 14 17 22 [0] [1] [2] [3] [4] [5] 11 7 8 11 14 17 22

Arrays vs Linked List Delete Operation 7 8 14 17 22 [0] [1] [2] [3] [4] [5] 7 8 11 14 17 22

Topics Linked List Concepts Creating and Managing Lists Doubly Linked Lists

Basic Node Definition Variable definition: ListNode* ListNodePtr; class ListNode { private: string item; // or T if using templates int count; ListNode *link; }; Variable definition: ListNode* ListNodePtr; Also notice "circularity"

Head Pointer Box labeled "head" not a node: ListNodePtr head; A simple pointer to a node Set to point to 1st node in list Head used to "maintain" start of list Assignment head->item = "Hello "; cin >> head->item; Also used as argument to functions Use NULL for node pointer. Considered "sentinel" for nodes. Indicates no further "links" after this node

Linked List Practice Step 1 of 4 Create new practice project Implement the node as a template class Define a new class for the node Private members for T data and Node* next Default constructor - Set link to null General constructor Set link to input pointer node Set item data to input parameter data Implement getters and setters Main() Must include both node.h and node.cpp Declare Node<string> temp("Hello", NULL); Note – cout sometimes behaves odd with template data coming back from getData methods

Assumes that member variables are public Accessing Node Data Assumes that member variables are public

Linked List Class Definition Version 2 Default constructor sets link to null class IntNode { public: IntNode() { data = 0; intNode = null; } IntNode(int theData, IntNode* theLink) : data(theData), link(theLink) { } IntNode* getLink() {return link;} int getData() {return data;} void setData(int theData) {data = theData;} void setLink(intNode* pointer) {link=pointer;} private: int data; intNode *link; }; IntNode* p1 = new IntNode; IntNode* p2 = new IntNode(42, p1); Remember shortcut! General constructor allows for built in link to next in list

Linked List Practice Step 2 of 4 Define another class that will represent the actual list Add private member variable which is Node<T>* head; Default constructor should set head to _________ General constructor should set head to input parameter Create a print method which loops through the linked list and calls the node getData method to display value of node In main() - LinkedList<string> list(&temp); Then call list.print();

Lost Nodes Pitfall – Don’t Lose Your Head

Inserting in the Middle of a Linked List

Linked List Practice Step 3 of 4 Write the insert method to add a new node to the linked list in sorted order Define a function that will prepend a node to tbe beginning of the list Node<T>* node = new Node<T>(n, NULL); node->setNext(head); head = node; Next, define the insert method If the list is empty (head == null), call prepend If the current head of the list is smaller than the new value, call prepend Else loop through the list until we find a node that is smaller than the new value. Create a new node and insert it into the list (see notes) if (head == NULL) prepend(n); else if (n < head->getData()) else { Node<T>* ptr = head; while (ptr->getNext() != NULL && ptr->getNext()->getData() < n)// look ahead one node and see if that node is smaller ptr = ptr->getNext(); Node<T>* temp = new Node<T>(n, ptr->getNext());// create the node and insert into list. ptr->setNext(temp); }

Searching for Nodes Must make "special" case for empty list Pseudocode: while (current doesn’t point to target node or last node) Make current point to next node in list if (current node points to target) return current pointer else return NULL while (cur->getData() != target && cur->getLink() != NULL) cur = cur->getLink(); if (cur->getData() == target) return here; else return NULL; Must make "special" case for empty list Not done here

Linked List Practice Step 4 of 4 Write the search method Loop through the list until you find the node that matches the data value Return the address of the found node or NULL if not found Write the remove method If the list is empty, do nothing If the head of the list matches the data value, advance the head to the next node in list Else loop through the list until node is found. Reset pointers and delete the node. template<class T> Node<T>* LinkedList<T>::search(T n) { Node<T>* ptr = head; while (ptr != NULL) { if (ptr->getData() == n) return ptr; ptr = ptr->getNext(); } return NULL; void LinkedList<T>::remove(T n) if (head == NULL) return; if (head->getData() == n) { Node<T>* temp = head; head = head->getNext(); delete temp; else { while (ptr->getNext() != NULL) { if (ptr->getNext()->getData() == n) { Node<T>* temp = ptr->getNext(); ptr->setNext(ptr->getNext()->getNext()); return;

Topics Linked List Concepts Creating and Managing Lists Doubly Linked Lists

Twice the Fun! Single is a lonely number – can only go in one direction! Doubly Linked List Links to the next node and another link to the previous node Can follow links in either direction NULL signifies the beginning and end of the list Can make some operations easier, e.g. deletion since we don’t need to search the list to find the node before the one we want to remove

Maintaining Double Linked List Each node now has 2 pointers 2) Update old head back ptr to new head 3) Reset the actual head 1) Allocate new head

Doubly Linked Lists class DoublyLinkedIntNode { public: DoublyLinkedIntNode (int theData, DoublyLinkedIntNode* previous, DoublyLinkedIntNode* next) : data(theData), nextLink(next), previousLink(previous) {} DoublyLinkedIntNode* getNextLink( ) const { return nextLink; } DoublyLinkedIntNode* getPreviousLink( ) const { return previousLink; } int getData( ) const { return data; } void setData(int theData) { data = theData; } void setNextLink(DoublyLinkedIntNode* pointer) { nextLink = pointer; } void setPreviousLink(DoublyLinkedIntNode* pointer) { previousLink = pointer; } private: int data; DoublyLinkedIntNode *nextLink; DoublyLinkedIntNode *previousLink; }; typedef DoublyLinkedIntNode* DoublyLinkedIntNodePtr;

Deleting a Node from a Doubly Linked Discard variable acts as a place holder Delete frees up memory

Key Takeaways Lists have the following components Nodes _________ for connection Heads and optionally tails Great for creating sorted lists of things Insertion sort works great Not as efficient as arrays but more dynamic and flexible

Destructors & Copy Constructors Destructor: ~LinkedList() Copy Constructor: LinkedList(LinkedList& l)