Linked Lists Ch 17 (Gaddis) Introduction to Linked Lists. Introduction to Linked Lists. Node Organization

Similar documents
Data Structures Using C++ 2E. Chapter 5 Linked Lists

Data Structures Using C++ 2E. Chapter 5 Linked Lists

Linked List as an ADT (cont d.)

Unordered Linked Lists

Linked Lists Linked Lists, Queues, and Stacks

Node-Based Structures Linked Lists: Implementation

A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:

LINKED DATA STRUCTURES

Lecture 12 Doubly Linked Lists (with Recursion)

Output: struct treenode{ int data; struct treenode *left, *right; } struct treenode *tree_ptr;

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

Basics of I/O Streams and File I/O

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists

Integrating the C++ Standard Template Library Into the Undergraduate Computer Science Curriculum

Abstract Data Type. EECS 281: Data Structures and Algorithms. The Foundation: Data Structures and Abstract Data Types

Questions 1 through 25 are worth 2 points each. Choose one best answer for each.

Short Notes on Dynamic Memory Allocation, Pointer and Data Structure

Algorithms and Data Structures Written Exam Proposed SOLUTION

C++ INTERVIEW QUESTIONS

An Incomplete C++ Primer. University of Wyoming MA 5310

CmpSci 187: Programming with Data Structures Spring 2015

Pointers and Linked Lists

DATA STRUCTURES USING C

C++FA 5.1 PRACTICE MID-TERM EXAM

Stacks. Linear data structures

Ordered Lists and Binary Trees

Algorithms and Data Structures

Data Structures and Algorithms

Quiz 4 Solutions EECS 211: FUNDAMENTALS OF COMPUTER PROGRAMMING II. 1 Q u i z 4 S o l u t i o n s

1. Relational database accesses data in a sequential form. (Figures 7.1, 7.2)

Common Data Structures

10CS35: Data Structures Using C

1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D.

D06 PROGRAMMING with JAVA

Course: Programming II - Abstract Data Types. The ADT Queue. (Bobby, Joe, Sue, Ellen) Add(Ellen) Delete( ) The ADT Queues Slide Number 1

Data Structures and Algorithms Lists

CS107L Handout 04 Autumn 2007 October 19, 2007 Custom STL-Like Containers and Iterators

Ch 7-1. Object-Oriented Programming and Classes

Curriculum Map. Discipline: Computer Science Course: C++

MAX = 5 Current = 0 'This will declare an array with 5 elements. Inserting a Value onto the Stack (Push)

ADTs,, Arrays, Linked Lists

Linked Lists: Implementation Sequences in the C++ STL

Data Structures and Data Manipulation

Linked Lists, Stacks, Queues, Deques. It s time for a chainge!

QUEUES. Primitive Queue operations. enqueue (q, x): inserts item x at the rear of the queue q

BSc (Hons) Business Information Systems, BSc (Hons) Computer Science with Network Security. & BSc. (Hons.) Software Engineering

CS 2112 Spring Instructions. Assignment 3 Data Structures and Web Filtering. 0.1 Grading. 0.2 Partners. 0.3 Restrictions

Analysis of a Search Algorithm

Cours de C++ Utilisations des conteneurs

Queue Implementations

Data Structures and Algorithms

Course: Programming II - Abstract Data Types. The ADT Stack. A stack. The ADT Stack and Recursion Slide Number 1

Sequences in the C++ STL

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

Introduction to data structures

Software Engineering Concepts: Testing. Pointers & Dynamic Allocation. CS 311 Data Structures and Algorithms Lecture Slides Monday, September 14, 2009

CHAPTER 4 ESSENTIAL DATA STRUCTRURES

COMPUTER SCIENCE. Paper 1 (THEORY)

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

COMP 356 Programming Language Structures Notes for Chapter 10 of Concepts of Programming Languages Implementing Subprograms.

recursion, O(n), linked lists 6/14

5. A full binary tree with n leaves contains [A] n nodes. [B] log n 2 nodes. [C] 2n 1 nodes. [D] n 2 nodes.

Cpt S 223. School of EECS, WSU

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

PES Institute of Technology-BSC QUESTION BANK

Recursive Implementation of Recursive Data Structures

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

The University of Alabama in Huntsville Electrical and Computer Engineering CPE Test #4 November 20, True or False (2 points each)

The Tower of Hanoi. Recursion Solution. Recursive Function. Time Complexity. Recursive Thinking. Why Recursion? n! = n* (n-1)!

C Dynamic Data Structures. University of Texas at Austin CS310H - Computer Organization Spring 2010 Don Fussell

Recursion. Slides. Programming in C++ Computer Science Dept Va Tech Aug., Barnette ND, McQuain WD

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

Data Structures Fibonacci Heaps, Amortized Analysis

El Dorado Union High School District Educational Services

Coding Rules. Encoding the type of a function into the name (so-called Hungarian notation) is forbidden - it only confuses the programmer.

Binary Heap Algorithms

Sample Questions Csci 1112 A. Bellaachia

Circular Linked List. Algorithms and Data Structures

Object Oriented Software Design II

- Easy to insert & delete in O(1) time - Don t need to estimate total memory needed. - Hard to search in less than O(n) time

CSE 211: Data Structures Lecture Notes VII

Project 4 DB A Simple database program

Converting a Number from Decimal to Binary

Sequential Data Structures

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Linked List Problems

Chapter 3: Restricted Structures Page 1

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays:

13 Classes & Objects with Constructors/Destructors

Abstract Data Types. Chapter 2

API for java.util.iterator. ! hasnext() Are there more items in the list? ! next() Return the next item in the list.

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator=

TREE BASIC TERMINOLOGIES

Transcription:

Linked Lists Ch 17 (Gaddis) Introduction to Linked Lists A data structure representing a A series of nodes chained together in sequence CS 3358 Summer I 2012 Jill Seaman - Each node points to one other node. A separate pointer (the ) points to the first item in the. The last element points to nothing () 1 2 Introduction to Linked Lists The nodes are dynamically allocated - The grows and shrinks as nodes are added/ removed. Linked s can easily insert a node between other nodes Linked s can easily delete a node from between other nodes Each node contains: Node Organization - data field may be organized as a structure, an object, etc. - a pointer that can point to another node data pointer 3 4

Empty List An empty contains 0 nodes. The points to (address 0) (There are no nodes, it s empty) Declaring the Linked List data type We will be defining a class for a linked data type that can store values of type double. The data type will describe the values (the s) and operations over those values. In order to define the values we must: - define a data type for the nodes - define a pointer variable () that points to the first node in the. 5 6 static int getobjectcount(); Declaring the Node data type Defining the Linked List variable Use a struct for the node type struct ListNode { double value; ListNode *next; ; (this is just a data type, no variables declared) next can hold the address of a ListNode. Define a pointer for the of the : ListNode * = ; It must be initialized to to signify the end of the. Now we have an empty linked : - it can also be - self-referential data structure 7 8 static int getobjectcount(); static int getobjectcount();

Using Linked List operations Equivalent to address 0 Used to specify end of the Use ONE of the following for : #include <iostream> #include <cstddef> to test a pointer for (these are equivalent): while (p)... <==> while (p!= )... if (!p)... <==> if (p == )... Basic operations: - create a new, empty - append a node to the end of the - insert a node within the - delete a node - display the linked - delete/destroy the - copy constructor (and operator=) 9 10 static int getobjectcount(); static int getobjectcount(); Linked List class declaration // file NumberList.h Linked List functions: constructor #include <cstddef> using namespace std; // for Constructor: sets up empty class NumberList { private: struct ListNode // the node data type { double value; // data struct ListNode *next; // ptr to next node ; ListNode *; // the public: NumberList(); NumberList(const NumberList & src); ~NumberList(); // file NumberList.cpp #include "NumberList.h" NumberList::NumberList() { = ; ; void appendnode(double); void insertnode(double); void deletenode(double); void displaylist(); 11 12

Linked List functions: appendnode Linked List functions: appendnode appendnode: adds new node to end of Algorithm: How to find the last node in the? Algorithm: Create a new node and store the data in it If the has no nodes (it s empty) Make point to the new node. Else Find the last node in the Make the last node point to the new node When defining operations, always consider special cases: Empty Make a pointer p point to the first element while (the node p points to) is not pointing to make p point to (the node p points to) is pointing to In C++: ListNode *p = ; while ((*p).next!= ) p = (*p).next; ListNode *p = ; while (p->next) p = p->next; First element, front of the (when pointer is involved) 13 14 <==> p=p->next is like i++ ListNode *p = ; Linked List functions: appendnode Traversing a Linked List void NumberList::appendNode(double num) { ListNode *newnode; // To point to the new node // Create a new node and store the data in it newnode = new ListNode; newnode->value = num; newnode->next = ; // If empty, make point to new node if (!) = newnode; else { ListNode *nodeptr; // To move through the nodeptr = ; // initialize to start of // traverse to find last node while (nodeptr->next) //it s not last nodeptr = nodeptr->next; //make it pt to next // now nodeptr pts to last node // make last node point to newnode nodeptr->next = newnode; 15 Visit each node in a linked, to - display contents, sum data, test data, etc. Basic process: set a pointer to point to what points to while pointer is not process data of current node go to the next node by setting the pointer to the pointer field of the current node end while 16

Linked List functions: displaylist Driver to demo NumberList void NumberList::displayList() { ListNode *nodeptr; //ptr to traverse the // start nodeptr at the of the nodeptr = ; // while nodeptr pts to something (not ), continue while (nodeptr) { //Display the value in the current node cout << nodeptr->value << endl; ListDriver.cpp //ListDriver.cpp: using NumberList #include "NumberList.h" int main() { //Move to the next node nodeptr = nodeptr->next; Or the short version: void NumberList::displayList() { ListNode *nodeptr; for (nodeptr = ; nodeptr; nodeptr = nodeptr->next) cout << nodeptr->value << endl; 17 // Define the NumberList ; // Append some values to the.appendnode(2.5);.appendnode(7.9);.appendnode(); // Display the values in the..displaylist(); return 0; Output: 2.5 7.9 18 Deleting a Node from a Linked List Deleting a node deletenode: removes node from, and deletes (deallocates) the removed node. Requires two pointers: - one to point to the node to be deleted - one to point to the node before the node to be deleted. previousnode nodeptr Change the pointer of the previous node to point to the node after the one to be deleted. previousnode previousnode->next = nodeptr->next; nodeptr Now just delete the nodeptr node Deleting 13 from the 19 20

Deleting a node After the node is deleted: previousnode delete nodeptr; nodeptr 5 19 21 Delete Node Algorithm Delete the node containing num If is empty, exit If first node is num make p point to first node make point to second node delete p else use p to traverse the, until it points to num or --as p is advancing, make n point to the node before if (p is not ) make n s node point to what p s node points to delete p s node 22 Linked List functions: deletenode void NumberList::deleteNode(double num) { if (!) return; // empty, exit ListNode *nodeptr; // to traverse the if (->value == num) { // if first node is num nodeptr = ; = nodeptr->next; delete nodeptr; else { ListNode *previousnode; // trailing node pointer nodeptr = ; // traversal ptr, set to first node // skip nodes not equal to num, stop at last while (nodeptr && nodeptr->value!= num) { previousnode = nodeptr; // save it! nodeptr = nodeptr->next; // advance it if (nodeptr) { // num is found, set links + delete previousnode->next = nodeptr->next; delete nodeptr; 23 // else: end of, num not found in, do nothing Driver to demo NumberList ListDriver.cpp // set up the NumberList ;.appendnode(2.5);.appendnode(7.9);.appendnode();.displaylist(); Nice test case, checks all three cases cout << endl << "remove 7.9:" << endl;.deletenode(7.9);.displaylist(); cout << endl << "remove 8.9: " << endl;.deletenode(8.9);.displaylist(); cout << endl << "remove 2.5: " << endl;.deletenode(2.5);.displaylist(); Output: 2.5 7.9 remove 7.9: 2.5 remove 8.9: 2.5 remove 2.5: 24

Destroying a Linked List The destructor must delete (deallocate) all nodes used in the To do this, use traversal to visit each node For each node, - save the address of the next node in a pointer - delete the node Linked List functions: destructor ~NumberList: deallocates all the nodes NumberList::~NumberList() { ListNode *nodeptr; // traversal ptr ListNode *nextnode; // saves the next node nodeptr = ; //start at of while (nodeptr) { nextnode = nodeptr->next; // save the next delete nodeptr; // delete current nodeptr = nextnode; // advance ptr 25 26 Inserting a Node into a Linked List Requires two pointers: - pointer to point to the node after the insertion point - pointer to point to node before point of insertion New node is inserted between the nodes pointed at by these pointers Inserting a Node into a Linked List New node created, new position located: previousnode nodeptr The before and after pointers move in tandem as the is traversed to find the insertion point - Like delete newnode 17 27 28

Inserting a Node into a Linked List Insert Node Algorithm Insertion completed: newnode 17 previousnode nodeptr 29 Insert node in a certain position Create the new node, store the data in it If is empty, make point to new node, new node to null else use p to traverse the, until it points to node after insertion point or --as p is advancing, make n point to the node before if p points to first node (n is null) make point to new node new node to p s node else make n s node point to new node 30 make new node point to p s node Insert Node Algorithm Linked List functions: insertnode Note that the insertnode implementation that follows assumes that the is sorted. The insertion point is - immediately before the first node in the that has a value greater than the value being inserted or - at the end if the value is greater than all items in the. Not always applicable, but it is a good demonstration of inserting a node in the middle of a. 31 insertnode: inserts num into middle of void NumberList::insertNode(double num) { ListNode *newnode; // ptr to new node ListNode *nodeptr; // ptr to traverse ListNode *previousnode; // node previous to nodeptr //allocate new node newnode = new ListNode; newnode->value = num; // empty, insert at front if (!) { = newnode; newnode->next = ; //else is on the next slide... 32

Linked List functions: insertnode else { // initialize the two traversal ptrs nodeptr = ; previousnode = ; Driver to demo NumberList ListDriver.cpp // skip all nodes less than num while (nodeptr && nodeptr->value < num) { previousnode = nodeptr; // save nodeptr = nodeptr->next; // advance if (previousnode == ) { //insert before first = newnode; newnode->next = nodeptr; else { previousnode->next = newnode; newnode->next = nodeptr; //insert after previousnode int main() { // set up the NumberList ;.appendnode(2.5);.appendnode(7.9);.appendnode();.insertnode(10.5);.displaylist(); return 0; Output: 2.5 7.9 10.5 What if num is bigger than all items in the? 33 34 Copy Constructor Pointers + dynamic allocation => deep copy Don t copy any pointers Linked List functions: copy constructor NumberList::NumberList(const NumberList & src) { = ; // initialize empty Initialize to For each item in the src (in order) append item.value to this // traverse src, append its values to end of this ListNode *nodeptr; for (nodeptr=src.; nodeptr; nodeptr=nodeptr->next) { appendnode(nodeptr->value); 35 36

Chapter 17 in Weiss book Elegant implementation of linked s It uses a er node - empty node, immediately before the first node in the - eliminates need for most special cases - internal traversals must skip that node - not visible to users of the class 37 Chapter 17 in Weiss book It uses three separate classes (w/ friend access) - LListNode (value+next ptr) - LListItr (an iterator) - LList (the linked, with operations) What is an iterator? - a reference/ptr to a specific element in a specific - Operations: advance: make it point to next element retrieve: return the value it points to (dereference) isvalid: returns true if not (it points to an element) 38 Circular linked Linked List variations - last cell s next pointer points to the first element. Doubly linked Linked List variations - each node has two pointers, one to the next node and one to the previous node - points to first element, tail points to last. - can traverse in reverse direction by starting at the tail and using p=p->prev. 39 40

Advantages of linked s (over arrays) A linked can easily grow or shrink in size. - The programmer doesn t need to predict how many values could be in the. - The programmer doesn t need to resize (copy) the when it reaches a certain capacity. When a value is inserted into or deleted from a linked, none of the other nodes have to be moved. Advantages of arrays (over linked s) Arrays allow random access to elements: array[i] - linked s allow only sequential access to elements (must traverse to get to i th element). Arrays do not require extra storage for links - linked s are impractical for s of characters or booleans (pointer value is bigger than data value). 41 42