CSE Lecture 12 – Linked Lists …

Slides:



Advertisements
Similar presentations
Chapter 25 Lists, Stacks, Queues, and Priority Queues
Advertisements

TK1924 Program Design & Problem Solving Session 2011/2012
TK1924 Program Design & Problem Solving Session 2011/2012
CS Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.
Linked Lists Geletaw S..
1
Copyright © 2003 Pearson Education, Inc. Slide 1.
Chapter 7 Constructors and Other Tools. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-2 Learning Objectives Constructors Definitions.
Chapter 17 Linked Data Structures. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives Nodes and Linked Lists Creating,
Copyright © 2003 Pearson Education, Inc. Slide 1 Computer Systems Organization & Architecture Chapters 8-12 John D. Carpinelli.
Chapter 3: Linked List Tutor: Angie Hui
Introduction to Computation and Problem
Lecture 15 Linked Lists part 2
1 Chapter 10 - Structures, Unions, Bit Manipulations, and Enumerations Outline 10.1Introduction 10.2Structure Definitions 10.3Initializing Structures 10.4Accessing.
Table 12.1: Cash Flows to a Cash and Carry Trading Strategy.
PP Test Review Sections 6-1 to 6-6
Inserting a Node into a Specified Position of a Linked List To create a node for the new item newNode = new Node(item); To insert a node between two nodes.
Chapter 17 Linked Lists.
Topic 12 The List ADT. 9-2 Objectives Examine list processing and various ordering techniques Define a list abstract data type Examine various list implementations.
COMP171 Fall 2005 Lists.
Chapter 4 Linked Lists. © 2005 Pearson Addison-Wesley. All rights reserved4-2 Preliminaries Options for implementing an ADT List –Array has a fixed size.
Singly Linked Lists What is a singly-linked list? Why linked lists?
Stacks, Queues, and Linked Lists
Lists Chapter 6 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved
Linked List A linked list consists of a number of links, each of which has a reference to the next link. Adding and removing elements in the middle of.
DATA STRUCTURES AND ALGORITHMS Prepared by İnanç TAHRALI
Linked Lists.
Linked Lists Chapter 4.
1111 Abstract Data Types Cpt S 223. School of EECS, WSU.
Linear Lists – Linked List Representation
Data Structures: A Pseudocode Approach with C
Data Structures ADT List
DATA STRUCTURES USING C++ Chapter 5
Chapter 24 Lists, Stacks, and Queues
Main Index Contents 11 Main Index Contents Shifting blocks of elements… Shifting blocks of elements… Model of a list object… Model of a list object… Sample.
11 Data Structures Foundations of Computer Science ã Cengage Learning.
Stack and Queues using Linked Structures Kruse and Ryba Ch 4.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 4: Linked Lists Data Abstraction & Problem Solving with.
Alan YorinksLecture 7 1 • Tonight we will look at:: • List ADT • Unsorted List • Sequential Search • Selection Sort • Sorted List • Binary Search.
Data Structures Using C++
Data Structures Part 2 Stacks, Queues, Trees, and Graphs Briana B. Morrison CSE 1302C Spring 2010.
Double-Linked Lists and Circular Lists
Chapter 1 Object Oriented Programming 1. OOP revolves around the concept of an objects. Objects are created using the class definition. Programming techniques.
1 DATA STRUCTURES. 2 LINKED LIST 3 PROS Dynamic in nature, so grow and shrink in size during execution Efficient memory utilization Insertion can be.
CSCI2100B Linked List Jeffrey
Copyright © 2012, Elsevier Inc. All rights Reserved. 1 Chapter 7 Modeling Structure with Blocks.
1 RA III - Regional Training Seminar on CLIMAT&CLIMAT TEMP Reporting Buenos Aires, Argentina, 25 – 27 October 2006 Status of observing programmes in RA.
Adding Up In Chunks.
Copyright © 2013 by John Wiley & Sons. All rights reserved. HOW TO CREATE LINKED LISTS FROM SCRATCH CHAPTER Slides by Rick Giles 16 Only Linked List Part.
Algorithm Analysis.
Linked Lists CENG 213 Data Structures.
1 hi at no doifpi me be go we of at be do go hi if me no of pi we Inorder Traversal Inorder traversal. n Visit the left subtree. n Visit the node. n Visit.
Essential Cell Biology
PSSA Preparation.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13 Pointers and Linked Lists.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 13 - Exception Handling Outline 13.1 Introduction 13.2 Exception-Handling Overview 13.3 Other.
1 Decidability continued…. 2 Theorem: For a recursively enumerable language it is undecidable to determine whether is finite Proof: We will reduce the.
Data Structure (Part I) Stacks and Queues. Introduction to Stack An stack is a ordered list in which insertion and deletions are made at one end. –The.
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.
Main Index Contents 11 Main Index Contents Abstract Model of a List Obj. Abstract Model of a List Obj. Insertion into a List Insertion into a List Linked.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Custom Templatized Data Structures.
COP3530 Data Structures600 Stack Stack is one the most useful ADTs. Like list, it is a collection of data items. Supports “LIFO” (Last In First Out) discipline.
1 Chapter 7 Stacks and Queues. 2 Stack ADT Recall that ADT is abstract data type, a set of data and a set of operations that act upon the data. In a stack,
1 Linked-list, stack and queue. 2 Outline Abstract Data Type (ADT)‏ Linked list Stack Queue.
A Doubly Linked List prevnextdata There’s the need to access a list in reverse order header dnode.
Chapter 5 Linked List by Before you learn Linked List 3 rd level of Data Structures Intermediate Level of Understanding for C++ Please.
“The desire for safety stands against every great and noble enterprise.” – Tacitus Thought for the Day.
A Doubly Linked List There’s the need to access a list in reverse order prev next data dnode header 1.
Chapter 9 Linked Lists.
Presentation transcript:

CSE 30331 Lecture 12 – Linked Lists … Array vs. Linked List Pointers & Nodes Singly linked list Doubly linked list Circular linked lists Header (dummy) node Implementing ADT’s Stack Queue

Reading Linked Lists Ford: Ch 9

Array vs. Linked List Arrays (& STL vectors) Direct access by index – O(1) Insertion & deletion requires shifting – O(n) Dynamically resizable only at one end May require copying of all values Pop & push at end – O(1) Unless resizing is involved Linked Lists ( & STL lists) Sequential access – O(n) Insertion & deletion without shifting – O(1) Dynamically resizable anywhere –O(1) Pop & push at either end – O(1)

Abstraction of a Linked List Singly Linked List front back Doubly Linked List

Linked List Nodes Each Node is like a piece of a chain To insert a new link, break the chain at the desired location and simply reconnect at both ends of the new piece.

Linked List Nodes Removal is like Insertion in reverse.

Node Composition (singly linked list) An individual Node is composed of two parts a Data field containing the data stored by the node a Pointer field containing the address of the next Node in the list.

Inserting at the Front of an empty Singly Linked List

Inserting at the Front of a nonempty Singly Linked List

Deleting From the Front of a Singly Linked List // front = NULL Deleting front of a 1-node list

Deleting From the Front of a Singly Linked List Deleting front of a multi-node list // front = front->next

Removing a Target Node front target prev curr // next

A stack as a NULL terminated singly linked list

Node data structure // forward declaration, just to keep the compiler happy template <typename T> class Stack; class Node { friend class Stack<T>; // let Stack access data & next public: Node(T value = T()) : data(value), next(NULL) { } private: T data; Node *next; };

Stack as a Singly Linked List template <typename T> class Stack { public: Stack(); ~Stack(); bool empty(); // true or false, status of stack T top(); // return copy of top node’s value void pop(); // remove top node void push(T value); // create new top node with value void clear(); // remove all nodes from stack private: Node<T> *topNode; };

Stack member functions template <typename T> Stack<T>::Stack() : topNode(NULL) { } Stack<T>::~Stack() { clear(); // make sure all memory is freed } bool Stack<T>::empty() { return (NULL == topNode);

Stack member functions template <typename T> T Stack<T>::top(){ if (empty()) throw(“in top() with Empty Stack”); return topNode->data; } void Stack<T>::pop() { if (! empty()) { Node<T> *temp = topNode; // point to top node topNode = topNode->next; // point around to next node delete temp; // free node memory

Stack member functions template <typename T> void Stack<T>::push(T value) { Node<T> *temp = new Node<T>(value); // create new Node temp->next = topNode; // new node points to top Node topNode = temp; // now new node IS top Node } void Stack<T>::clear() { while(! empty()) pop();

Stack Tester #include "myStack.h" #include <string> #include <iostream> using namespace std; int main () { Stack<string> S; string name; cout << "Enter names ('done' to quit, 'purge' to clear)\n"; cin >> name; // get first name while (name != "done") { if (name == "purge") S.clear(); else S.push(name); cin >> name; // get another name } cout << "Names entered -- NOW reversed --\n"; while (! S.empty()) { cout << S.top() " "; S.pop(); cout << endl; return 0;

Queue as a Null Terminated Singly Linked List Need front and back pointers so we have access to both ends of list

Node data structure (Queue version ~ same as Stack) // forward declaration, just to keep the compiler happy template <typename T> class Queue; class Node { friend class Queue<T>; // let Queue access data & next public: Node(T value = T()) : data(value), next(NULL) { } private: T data; Node *next; };

Queue as a Singly Linked List template <typename T> class Queue { public: Queue(); ~Queue(); bool empty(); // true or false, status of queue T front(); // return copy of first value void pop(); // remove first node void push(T value); // create new last node with value void clear(); // remove all nodes from queue private: Node<T> *first, *last; };

Queue member functions template <typename T> Queue<T>::Queue() : first(NULL), last(NULL) { } Queue<T>::~Queue() { // same as Stack clear(); // make sure all memory is freed } bool Queue<T>::empty() {// essentially same as Stack return (NULL == first);

Queue member functions template <typename T> T Queue<T>::front(){ if (empty()) throw(“in front() with Empty Queue”); return first->data; } void Queue<T>::pop() { if (! empty()) { Node<T> *temp = first; // point to first node first = first->next; // point around to next node delete temp; // free node memory

Queue member functions template <typename T> void Queue<T>::push(T value) { Node<T> *temp = new Node<T>(value); // create new Node if (empty()) first = temp; // new last node is also first node else last->next = temp; // new last node follows old last = temp; // now new node IS last Node } void Queue<T>::clear() { while(! empty()) pop();

Doubly Linked Lists Singly linked list only allow easy traversal in one direction (forward) Doubly linked lists allow easy traversal both directions (forward and backward) The list can be linear Having NULL pointers at both ends The list can be circular Having each end point back to the other Usually this is implemented with a header node That contains no data That points to itself when list is empty

Circular Doubly Linked Lists A Watch Band provides a good Real Life analogue for this Data Structure

Circular Doubly Linked Lists Implemented on a Computer it might look something like this.

Empty and Non Empty Doubly Linked List

Implementing a Circular Doubly Linked List // forward declaration, just to keep the compiler happy template <typename T> class LinkedList; class Node { friend class LinkedList<T>; // let LinkedList access data & next public: Node(T value = T()) : data(value), next(NULL), prev(NULL) { } private: T data; Node *next, *prev; };

LinkedList (Circular and Doubly Linked) template <typename T> class LinkedList { public: LinkedList(); ~LinkedList(); int size(); // number of nodes in list T get(int pos); // return copy of value at pos void erase(int pos); // remove first node void insert(T value, int pos); // create new node with value at pos void clear(); // remove all nodes from queue int find(T value); // return position of first node with value private: Node<T> *last, // indicate beginning and end of list *current; // indicates current node int numNodes, // number of nodes in list currentPos; // indicates current position void moveTo(int pos); // moves current to desired Node };

LinkedList member functions template <typename T> LinkedList<T>::LinkedList() : numNodes(0), currentPos(-1) { last = new Node<T>; last->next = last; last->prev = last; current = last; // point to the header } LinkedList<T>::~LinkedList() clear(); // make sure all Node memory is freed delete last; // free the header Node memory

LinkedList member functions template <typename T> int LinkedList<T>::size() { return numNodes; } void LinkedList<T>::clear() while(size() > 0) erase(0); // remove all nodes

LinkedList member functions template <typename T> void LinkedList<T>::moveTo(int pos) { if ((pos < 0)|| (size() <= pos)) throw range_error(“LinkedList::moveTo() pos out of range”); while (currentPos < pos) // move forward along list current = current->next; currentPos++; } while (currentPos > pos) // move backward along list current = current->prev; currentPos--;

LinkedList member functions template <typename T> T LinkedList<T>::get(int pos) { try moveTo(pos); // move to indicated position in list } catch (exception &e) cerr << “Error from LinkedList::get()\n”; cerr << e.what(); exit 1; return current->data; // return value of Node

LinkedList member functions template <typename T> int LinkedList<T>::find(T value) { current = last->next; // point to first Node currentPos = 0; while (current != last) // move forward along list if (current->data == value) break; current = current->next; currentPos++; } if (current == last) currentPos = -1; return currentPos;

Deleting a Node at a Position // unlink the node (*curr) from the list curr->prev->next = curr->next; curr->next->prev = curr->prev; delete curr;

LinkedList member functions template <typename T> void LinkedList<T>::erase(int pos) { try { moveTo(pos); // move to indicated position in list } catch (exception &e) cerr << “Error from LinkedList::get()\n”; cerr << e.what(); exit 1; current->prev->next = current->next; // point around Node forward current->next->prev = current->prev; // point around Node backward delete current; // free Node memory

Inserting a Node at a Position // insert newNode before curr newNode->prev = curr->prev; newNode->next = curr; curr->prev->next = newNode; curr->prev = newNode;

LinkedList member functions template <typename T> void LinkedList<T>::insert(T value, int pos) { try { moveTo(pos); // move to indicated position in list } catch (exception &e) cerr << “Error from LinkedList::get()\n”; cerr << e.what(); exit 1; Node<T> *newNode = new Node(value); // make a new Node with value newNode->prev = current->prev; // point back at previous Node newNode->next = current; // have it point to new Node current->prev->next = newNode; // point forward to next Node current->prev = newNode; // have it point to new Node

So what is missing? Copy Constructor & Assignment Operator Need a deep copy Traverse source list Copy each node Insert in destination list Comparison Operator (==) Compare list lengths, and if equal … Traverse both lists Compare corresponding nodes

Copy Constructor template <typename T> LinkedList<T>::LinkedList(LinkedList<T>& theList) : numNodes(0), currentPos(-1) { last = new Node<T>; last->next = last; last->prev = last; current = last; // point to the header int pos(0); // start at dummy node while (pos < theList.size()) // while nodes in theList this->insert(theList.get(pos),pos)); // copy node and insert pos++; // move forward }

Assignment Operator (=) template <typename T> LinkedList<T>& LinkedList<T>::operator=(LinkedList<T>& theList) { if (this == &theList) return; // same lists, nothing to do LinkedList<T> *newList; int pos(0); // start at dummy node while (pos < theList.size()) // while nodes in theList newList.insert(theList.get(pos),pos)); // copy node and insert pos++; // move forward } return newList;

Comparison (==) template <typename T> bool LinkedList<T>::operator==(LinkedList<T>& theList) { if (this == &theList) return true; // same lists, nothing to do if (this->size() != theList.size()) return false; // lists have different number of values bool same(true); // assume the same int pos(0); // start at first node while (same && (pos < size()) // while same and more nodes if (this->get(pos) != theList.get(pos)) same = false; // nodes differ so lists do, too pos++; // move forward } return same;

Comparison (==) (more efficient, without function calls) template <typename T> bool LinkedList<T>::operator==(LinkedList<T>& theList) { if (this == &theList) return true; // same lists, nothing to do if (this->numNodes != theList.numNodes) return false; // lists have different number of values bool same(true); // assume the same Node<T> *nodeThis(this->last->next); // start at first node Node<T> *nodeThat(theList.last->next); // start at first node while (same && (nodeThis != last) // while same and more nodes if (nodeThis->data != nodeThat->data) same = false; // nodes differ so lists do, too nodeThis = nodeThis->next; // move forward nodeThat = nodeThat->next; // move forward } return same;