CSE 143. Linked Lists. Linked Lists. Manipulating Nodes (1) Creating Nodes. Manipulating Nodes (3) Manipulating Nodes (2) CSE 143 1

Similar documents
Common Misunderstandings from Exam 1 Material

C++ - Lesson 2 This is a function prototype. a' is a function that takes an integer array argument and returns an integer pointer.

CMSC 341 Lecture 10 Binary Search Trees

Concepts (this lecture) CSC 143. Classes with Dynamically Allocated Data. List of ints w/dups (cont.) Example: List of ints with dups.

Part I: Short Answer (12 questions, 65 points total)

ComS 228 Exam 1. September 27, 2004

Pointers, Dynamic Data, and Reference Types

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

An Introduction to C++

Binary Tree Node Relationships. Binary Trees. Quick Application: Expression Trees. Traversals

Binary Trees. For example: Jargon: General Binary Trees. root node. level: internal node. edge. leaf node. Data Structures & File Management

CSC 210, Exam Two Section February 1999

A506 / C201 Computer Programming II Placement Exam Sample Questions. For each of the following, choose the most appropriate answer (2pts each).

Dynamic Data Structures

Object-Oriented Principles and Practice / C++

Object Oriented Design

Ch. 12: Operator Overloading

CSE 333 Midterm Exam 2/14/14

KOM3191 Object Oriented Programming Dr Muharrem Mercimek OPERATOR OVERLOADING. KOM3191 Object-Oriented Programming

And Even More and More C++ Fundamentals of Computer Science

Pointers! Arizona State University 1

Object-Oriented Principles and Practice / C++

Link-Based Implementations. Chapter 4

CSE143 Exam with answers Problem numbering may differ from the test as given. Midterm #2 February 16, 2001

The issues. Programming in C++ Common storage modes. Static storage in C++ Session 8 Memory Management

double d0, d1, d2, d3; double * dp = new double[4]; double da[4];

Do not write in this area A.1 A.2 A.3 A.4 A.5 A.6 B.1 B.2 B.3 TOTAL. Maximum possible points:

Assignment 4: SkipList

Lecture 18 Tao Wang 1

CPSC 427a: Object-Oriented Programming

ADT: Design & Implementation

Chapter 10. Pointers and Dynamic Arrays. Copyright 2016 Pearson, Inc. All rights reserved.

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

CSE 100: C++ TEMPLATES AND ITERATORS

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

CS24 Week 3 Lecture 1

Object-Oriented Principles and Practice / C++

Chapter 10 Pointers and Dynamic Arrays. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo

Department of Computer Science & Engineering Indian Institute of Technology Kharagpur. Practice Sheet #10

CSE 333 Midterm Exam July 24, Name UW ID#

Suppose we find the following function in a file: int Abc::xyz(int z) { return 2 * z + 1; }

Pointers. A pointer value is the address of the first byte of the pointed object in the memory. A pointer does not know how many bytes it points to.

ICOM 4035 Data Structures. Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department

Chapter 17: Linked Lists

Data Structures in C. C Programming and Software Tools. N.C. State Department of Computer Science

CS32 Discussion Sec.on 1B Week 2. TA: Zhou Ren

Documentation. Programming / Documentation Slide 42

SETS AND MAPS. Chapter 9

Elementary Data Structures: Lists

Classes and Objects. Class scope: - private members are only accessible by the class methods.

CSE 333 Midterm Exam 5/10/13

Assignment of Structs

Assignment of Objects

CSCI-1200 Data Structures Spring 2018 Lecture 8 Templated Classes & Vector Implementation

CSE 303: Concepts and Tools for Software Development

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

Lab 2: ADT Design & Implementation

Fast Introduction to Object Oriented Programming and C++

Short Notes of CS201

Linked List Practice Questions

Chapter 17: Linked Lists

CS201 Some Important Definitions

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

Lecture 5. Function Pointers

CS201 - Introduction to Programming Glossary By

CSCI-1200 Data Structures Fall 2018 Lecture 7 Templated Classes & Vector Implementation


CS304 Object Oriented Programming Final Term

More About Classes. Gaddis Ch. 14, CS 2308 :: Fall 2015 Molly O'Neil

Intermediate Programming & Design (C++) Classes in C++

THE NAME OF THE CONSTRUCTOR AND DESTRUCTOR(HAVING (~) BEFORE ITS NAME) FUNCTION MUST BE SAME AS THE NAME OF THE CLASS IN WHICH THEY ARE DECLARED.

CSE 333 Midterm Exam Cinco de Mayo, 2017 (May 5) Name UW ID#

ECE 2400 Computer Systems Programming Fall 2018 Topic 7: Concrete Data Types

CSE 333 Midterm Exam Sample Solution 5/10/13

CA341 - Comparative Programming Languages

18. Dynamic Data Structures I. Dynamic Memory, Addresses and Pointers, Const-Pointer Arrays, Array-based Vectors

Outline. Dynamic Memory Classes Dynamic Memory Errors In-class Work. 1 Chapter 10: C++ Dynamic Memory

Linked List using a Sentinel

Advanced Systems Programming

Largest Online Community of VU Students

Definition of Stack. 5 Linked Structures. Stack ADT Operations. ADT Stack Operations. A stack is a LIFO last in, first out structure.

Special Member Functions

PIC 10B Lecture 1 Winter 2014 Homework Assignment #3

Chapter 10 Introduction to Classes

21. Dynamic Datatypes and Memory Management

CSCE 110 PROGRAMMING FUNDAMENTALS

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

Classes. Christian Schumacher, Info1 D-MAVT 2013

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012

CSE 333. Lecture 11 - constructor insanity. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington

Determine a word is a palindrome? bool ispalindrome(string word, int front, int back) { Search if a number is in an array

CpSc212 Goddard Notes Chapter 10. Linked Lists

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

C++: Const Function Overloading Constructors and Destructors Enumerations Assertions

Class Vector: Interface CSE 143. Dynamic Memory In Classes [Chapter 4, p ] Vector Implementation. Many Ways to Implement. Draw the picture!

Software Design and Analysis for Engineers

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

SCJ2013 Data Structure & Algorithms. Binary Search Tree. Nor Bahiah Hj Ahmad

Lecture 10 Notes Linked Lists

Transcription:

CSE 143 Linked Lists [Chapter 4; Chapter 6, pp. 265-271] Linked Lists A linked list is a collection of dynamically allocated nodes Each node contains at least one member (field) that points to another node in the list. In the simplest case, each node has two members: a data item and a link field which points to the successor node. Example: a list of 3 integers: head 4 8 16 265 266 Creating Nodes First we ll declare a struct to represent a node: struct Node { int data; Node* next; ; Now we can create new nodes: Node* p; p = new Node; p->data = 100; // shorthand for: (*p).data = 100 p->next = NULL; // shorthand for: (*p).next = NULL Manipulating Nodes (1) Draw the picture that results from the following code: Node* front; Node* temp; front = new Node; front->data = 1; 267 268 Manipulating Nodes (2) Manipulating Nodes (3) front->next = new Node; // add a node front->next->data = 2; front->next->next = NULL; temp = new Node; // add node between two others temp->data = 17; temp->next = front->next; front->next = temp; temp = front; front = front->next; delete temp; // delete a node 269 270 CSE 143 1

Example: Set of Ints Re-implement class IntSet (set of integers with no duplicates) -- no change to interface(!) Use linked list to represent set Same operations as before Construct empty set Add/remove numbers from set Search for number in set, report size of set Stream output Add other operations needed for full C++ class Copy constructor, destructor, assignment 271 IntSet Representation In intset.h class IntSet{ private: // Representation: Single-linked list Struct Node { // one node in the list int val; // integer value Node * next; // pointer to next ; // node or NULL Node * first; // pointer to first node // in the list, or // NULL if this IntSet // is empty. 272 Constructor List Traversal - size In intset.cpp // Construct empty IntSet IntSet::IntSet( ) { Several operations require a list traversal -- sequence through the nodes until reaching NULL at the end. Example: // Yield the size of this IntSet int IntSet::size( ) const { Node * p; // current element int n; // # nodes counted 273 n = 0; n++; return n; 274 size (cont) Example: This takes O(n) time. Could be O(1) if we kept track of set size as items added/removed. Membership test // = n is in this IntSet bool IntSet::isMember(int n) const { Node * p; // current element while (p!= NULL && p->val!= n) return (p!= NULL); Notice how this depends on && not evaluating its second argument if the first one is false WARNING: Never dereference a pointer p (p->x) unless you are absolutely sure p!=null (p!=0). 275 276 CSE 143 2

Stream Output (1) // Print IntSet t on s as {e1,e2,e3,,en ostream& operator<< (ostream &s, const IntSet & t) { IntSet::Node * p;// current element s << { p = t.first; s << p->val; Stream Output (2) while (p!=null){ s <<, << p->val; return (s << ); operator<< is a friend of IntSet. It can access type Node, but it must explicitly say which Node: IntSet::Node 277 278 Add New Element Since the list is unordered, we can add new elements onto the front of the list // Add n to this IntSet if not already in void IntSet::add(int n) { if (!ismember(n)){ Node *p = new Node; p->val = n; p->next = first; first = p; Cost? O(1)? O(n)? If the list were sorted (i.e., list position mattered), what would have to be different? 279 Delete (1) Need to find the number, then remove its node from the list // Remove n from this IntSet if present void IntSet::remove(int n) { Node * while (p!= NULL && p->val!= n) // p->val==n; remove node p from the // list and then delete p ----------------------------- What goes on the blank line? 280 Delete (2) To remove node p, we need to update the next pointer in the previous node. Use another pointer prev with prev->next=p, where p is the node we want to delete. So, Node * prev = first; Node * p = first->next; while (p!= NULL && p->val!= n){ prev = p; prev->next = p->next; Everything ok? 281 Delete (3) Bugs If the list is empty, first->next is an error (Why?) If the number to be deleted is in the first list node, we need to update first, not the next field of some node. 282 CSE 143 3

Delete (4) Final version // Remove n from this IntSet if present void IntSet::remove(int n) { Node * p; // current node Node * prev; // prev. node (prev->next=p) // special case: empty list if (first == NULL) return; // special case: delete 1st node if (first->val == n) { p = first->next; delete first; first = p; return; 283 Delete (5) Final version (cont) // Search non-empty list for n prev = first; p = first->next; while (p!= null && p->val!= n) { prev = p; // post (p==null) or (p->val==n) prev->next = p->next; 284 Standard Operations For a complete class we need to add a copy constructor, destructor, and assignment. These require different combinations of two operations Destroy -- ensure that all nodes on the current list have been deleted properly (destructor, assignment) Copy -- make a deep copy of the nodes belonging to another IntSet (copy constructor, assignment) Implement Destroy and Copy as private member functions -- avoid duplicating code. Copy (1) Store a deep copy of another IntSet in this one Makes no assumption about previous contents of this IntSet Caller must ensure any previously allocated nodes have already been reclaimed first. // Store a copy of s in this IntSet void IntSet::Copy(const IntSet &s) { Node * last; // last node added to // this IntSet so far Node * p // first node in s not // yet copied Node * q; 285 286 Copy (2) // If s is empty, set this IntSet empty if (s.first == NULL){ return; // copy first node of non-empty IntSet s first = new Node; first->val = s.first->val; first->next = NULL; Note difference between. to select fields and -> to follow pointer then select field 287 Copy (3) // copy nodes after the first p = s.first->next; last = first; // create new node q = new Node; q->val = p->val; q->next = NULL; // add new node to end of copied list last->next = q; last = q; 288 CSE 143 4

Destroy Only trick here is to watch assignment order // Deallocate the nodes in this IntSet void IntSet::Destroy( ) { Node * p; // first node not yet deleted Node * temp; tem p = temp; 289 Standard Class Members Given those operations, the rest is simple // Destructor IntSet::~IntSet( ) { Destroy( ); // Copy constructor IntSet::IntSet(const IntSet & val) { Copy(val); // Assignment IntSet & IntSet::operator= (const IntSet & val) { if (this!= &val) { Destroy( ); Copy(val); return *this 290 CSE 143 5