Linked Lists Eric Roberts CS 106B February 8, 2013.

Slides:



Advertisements
Similar presentations
Pointers.
Advertisements

Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
Chapter6 LISTS AND STRINGS. Outline 1. List Specifications 2. List Implementations (a) Class Templates (b) Contiguous (c) Simply Linked (d) Simply Linked.
Dynamic Allocation Eric Roberts CS 106B February 4, 2013.
The Assembly Language Level
Sets and Maps Chapter 9. Chapter 9: Sets and Maps2 Chapter Objectives To understand the Java Map and Set interfaces and how to use them To learn about.
COMP103 - Linked Lists (Part A)1 Chapter 17 Truly dynamic memory management.
Lecture 4 Sept 4 Goals: chapter 1 (completion) 1-d array examples Selection sorting Insertion sorting Max subsequence sum Algorithm analysis (Chapter 2)
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 13 Pointers and Linked Lists.
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
1 Data Structures Data Structures Topic #2. 2 Today’s Agenda Data Abstraction –Given what we talked about last time, we need to step through an example.
Guide To UNIX Using Linux Third Edition
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
Chapter 3: Arrays, Linked Lists, and Recursion
Linking Objects Together References are particularly important in computer science because they make it possible to represent the relationship among objects.
Functions in C++ Eric Roberts CS 106B January 9, 2013.
Pointer Data Type and Pointer Variables
Chapter 7—Objects and Memory The Art and Science of An Introduction to Computer Science ERIC S. ROBERTS Java Objects and Memory C H A P T E R 7 Yea, from.
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 © 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.
Chapter 7—Objects and Memory The Art and Science of An Introduction to Computer Science ERIC S. ROBERTS Java Objects and Memory C H A P T E R 7 Yea, from.
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.
Object-Oriented Programming in C++
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
Pointers OVERVIEW.
1 Advanced Issues on Classes Part 3 Reference variables (Tapestry pp.581, Horton 176 – 178) Const-reference variables (Horton 176 – 178) object sharing:
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Linked List. Iterators Operation to find a link, deleting, and inserting before or after a specified link, also involve searching through the list to.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 16. Linked Lists.
Chapter 10 Hashing. The search time of each algorithm depend on the number n of elements of the collection S of the data. A searching technique called.
Chapter 11 Hash Tables © John Urrutia 2014, All Rights Reserved1.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process.
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department.
Data Structures & Algorithms
Generic lists Vassilis Athitsos. Problems With Textbook Interface? Suppose that we fix the first problem, and we can have multiple stacks. Can we have.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
2005MEE Software Engineering Lecture 7 –Stacks, Queues.
Sets and Maps Chapter 9. Chapter Objectives  To understand the Java Map and Set interfaces and how to use them  To learn about hash coding and its use.
This document is copyright (C) Stanford Computer Science and Marty Stepp, licensed under Creative Commons Attribution 2.5 License. All rights reserved.
This document is copyright (C) Stanford Computer Science and Marty Stepp, licensed under Creative Commons Attribution 2.5 License. All rights reserved.
CHAPTER 51 LINKED LISTS. Introduction link list is a linear array collection of data elements called nodes, where the linear order is given by means of.
Linked Lists Data Structures and Algorithms CS 244 Brent M. Dingle, Ph.D. Department of Mathematics, Statistics, and Computer Science University of Wisconsin.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
Arrays, Link Lists, and Recursion Chapter 3. Sorting Arrays: Insertion Sort Insertion Sort: Insertion sort is an elementary sorting algorithm that sorts.
Implementing Queues Eric Roberts CS 106B February 13, 2013.
List Structures What is a list? A homogeneous collection of elements with a linear relationship between the elements linear relationship - each element.
Linked Lists Source: presentation based on notes written by R.Kay, A. Hill and C.Noble ● Lists in general ● Lists indexed using pointer arrays ● Singly.
Lecture 6 of Computer Science II
Pointers and Linked Lists
Module 11: File Structure
Pointers and Linked Lists
CS 215 Final Review Ismail abumuhfouz Fall 2014.
Editor Buffers Eric Roberts CS 106B February 6, 2013.
CSE 143 Linked Lists [Chapter , 8.8] 3/30/98.
Please visit
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Chapter 16-2 Linked Structures
Introduction to Classes
Linked List (Part I) Data structure.
Pointers, Dynamic Data, and Reference Types
Chapter 7—Objects and Memory
Chapter 7—Objects and Memory
Data Structures & Algorithms
Five-Minute Review What are local/instance/class variables? What about constants? What is an array? How do we locally declare an array of 5 integers? How.
Presentation transcript:

Linked Lists Eric Roberts CS 106B February 8, 2013

In Our Last Episode... On Wednesday, I talked about command-line editors and introduced the buffer.h interface, which exports a class called EditorBuffer.On Wednesday, I talked about command-line editors and introduced the buffer.h interface, which exports a class called EditorBuffer. Our goal for the week is to implement the EditorBuffer class in three different ways and to compare the algorithmic efficiency of the various options. Those representations are:Our goal for the week is to implement the EditorBuffer class in three different ways and to compare the algorithmic efficiency of the various options. Those representations are: A simple array model, which I introduced last time.1. A two-stack model that uses a pair of character stacks.2. A linked-list model that uses pointers to indicate the order.3. For each model, we’ll calculate the complexity of each of the six fundamental methods in the EditorBuffer class. Some operations will be more efficient with one model, others will be more efficient with a different one.For each model, we’ll calculate the complexity of each of the six fundamental methods in the EditorBuffer class. Some operations will be more efficient with one model, others will be more efficient with a different one.

Linking Objects Together Pointers are important in programming because they make it possible to represent the relationship among objects by linking them together in various ways. C++ marks the end of linked list using the constant NULL, which signifies a pointer that does not have an actual target. In diagrams, the NULL value marking the end of a list is often indicated by drawing a diagonal line across the box. The simplest example of a linked structure (which appears first in Chapter 12 and is used throughout the later chapters) is called a linked list, in which each object in a sequence contains a reference to the one that follows it: data NULL

The Beacons of Gondor Minas Tirith Amon DînEilenachNardolErelasMin- Rimmon CalenhadHalifirienRohan For answer Gandalf cried aloud to his horse. “On, Shadowfax! We must hasten. Time is short. See! The beacons of Gondor are alight, calling for aid. War is kindled. See, there is the fire on Amon Dîn, and flame on Eilenach; and there they go speeding west: Nardol, Erelas, Min-Rimmon, Calenhad, and the Halifirien on the borders of Rohan.” —J. R. R. Tolkien, The Return of the King, 1955 In a scene that was brilliantly captured in Peter Jackson’s film adaptation of The Return of the King, Rohan is alerted to the danger to Gondor by a succession of signal fires moving from mountain top to mountain top. This scene is a perfect illustration of the idea of message passing in a linked list.

The Beacons of Gondor

Minas Tirith Amon DînEilenachNardolErelasMin- Rimmon CalenhadHalifirienRohan For answer Gandalf cried aloud to his horse. “On, Shadowfax! We must hasten. Time is short. See! The beacons of Gondor are alight, calling for aid. War is kindled. See, there is the fire on Amon Dîn, and flame on Eilenach; and there they go speeding west: Nardol, Erelas, Min-Rimmon, Calenhad, and the Halifirien on the borders of Rohan.” —J. R. R. Tolkien, The Return of the King, 1955 In a scene that was brilliantly captured in Peter Jackson’s film adaptation of The Return of the King, Rohan is alerted to the danger to Gondor by a succession of signal fires moving from mountain top to mountain top. This scene is a perfect illustration of the idea of message passing in a linked list.

Message Passing in Linked Structures struct Tower { string name; /* The name of this tower */ Tower *link; /* Pointer to the next tower */ }; /* * Function: createTower(name, link); * * Creates a new Tower with the specified values. */ Tower *createTower(string name, Tower *link) { Tower *tp = new Tower; tp->name = name; tp->link = link; return tp; } /* * Function: signal(start); * * Generates a signal beginning at start. */ void signal(Tower *start) { if (start != NULL) { cout name << endl; signal(start->link); } To represent this message-passing image, you might use a definition such as the one shown on the right. Minas Tirith Amon Dîn Eilenach Nardol Erelas Min-Rimmon Calenhad Halifirien Rohan You can then initialize a chain of Tower structures, like this: Calling signal on the first tower sends a message down the chain.

Adding Links to Correct Errors Suppose you’re Thomas Jefferson and that you’re writing timeless prose to mark our nation’s founding. Of the British outrages, you’ve written that “our repeated petitions have been answered by repeated injury.” Now someone wants you to add the word “only” after “answered” in the finished text. What do you do?

List-Based Buffers The list-based model of the EditorBuffer class uses pointers to indicate the order of characters in the buffer. For example, the buffer containingThe list-based model of the EditorBuffer class uses pointers to indicate the order of characters in the buffer. For example, the buffer containing a b c d e is modeled conceptually like this:

Representing the Cursor The diagram on the preceding slide did not indicate the cursor position, mostly because doing so is a bit tricky.The diagram on the preceding slide did not indicate the cursor position, mostly because doing so is a bit tricky. If a list contains five cells, as in this example, there are six positions for the cursor. Thus, it is impossible to represent all of the possible positions by pointing to some cell.If a list contains five cells, as in this example, there are six positions for the cursor. Thus, it is impossible to represent all of the possible positions by pointing to some cell. One standard strategy for solving this problem is to allocate an extra cell (usually called a dummy cell) at the beginning of the list, and then represent the position of the cursor by pointing to the cell before the insertion point. Thus, if the cursor is between the c and the d, the five-character buffer would look like this:One standard strategy for solving this problem is to allocate an extra cell (usually called a dummy cell) at the beginning of the list, and then represent the position of the cursor by pointing to the cell before the insertion point. Thus, if the cursor is between the c and the d, the five-character buffer would look like this:

Methods in the EditorBuffer Class buffer.moveCursorForward() Moves the cursor forward one character (does nothing if it’s at the end). buffer.moveCursorBackward() Moves the cursor backward one character (does nothing if it’s at the beginning). buffer.moveCursorToStart() Moves the cursor to the beginning of the buffer. buffer.moveCursorToEnd() Moves the cursor to the end of the buffer. buffer.insertCharacter(ch) Inserts the character ch at the cursor position and advances the cursor past it. buffer.deleteCharacter() Deletes the character after the cursor, if any. buffer.getText() Returns the contents of the buffer as a string. buffer.getCursor() Returns the position of the cursor.

/* * Implementation notes * * In the linked-list implementation of the buffer, the characters in the * buffer are stored in a list of Cell structures, each of which contains * a character and a pointer to the next cell in the chain. To simplify * the code used to maintain the cursor, this implementation adds an extra * "dummy" cell at the beginning of the list. The following diagram shows * a buffer containing "ABC" with the cursor at the beginning: * * * start | o--+---==>| | -->| A | -->| B | -->| C | * / / / / * cursor | o--+-- | o--+-- | o--+-- | o--+-- | / | * */ struct Cell { char ch; Cell *link; }; /* Data fields required for the linked-list representation */ Cell *start; /* Pointer to the dummy cell */ Cell *cursor; /* Pointer to cell before cursor */ List-Based Private Data for Buffer

List Editor Simulation *Iacxde a c x d e ^ *J ^ *F ^ *Ib a b c x d e ^ *F ^ *D a b c d e ^ * start cursor acxde b

/* * File: buffer.cpp (list version) * * This file implements the EditorBuffer class using a linked * list to represent the buffer. */ #include #include "buffer.h" using namespace std; /* * Implementation notes: EditorBuffer constructor * * This function initializes an empty editor buffer represented as a * linked list. In this representation, the empty buffer contains a * "dummy" cell whose ch field is never used. The constructor must * allocate this dummy cell and set the internal pointers correctly. */ EditorBuffer::EditorBuffer() { start = cursor = new Cell; start->link = NULL; } List-Based Buffer Implementation

/* * File: buffer.cpp (list version) * * This file implements the EditorBuffer class using a linked * list to represent the buffer. */ #include #include "buffer.h" using namespace std; /* * Implementation notes: EditorBuffer constructor * * This function initializes an empty editor buffer represented as a * linked list. In this representation, the empty buffer contains a * "dummy" cell whose ch field is never used. The constructor must * allocate this dummy cell and set the internal pointers correctly. */ EditorBuffer::EditorBuffer() { start = cursor = new Cell; start->link = NULL; } /* * Implementation notes: EditorBuffer destructor * * The destructor must delete every cell in the buffer. Note that the loop * structure is not exactly the standard for loop pattern for processing * every cell within a linked list. The complication that forces this * change is that the body of the loop can't free the current cell and * later have the for loop use the link field of that cell to move to * the next one. To avoid this problem, this implementation copies the * link pointer before calling delete. */ EditorBuffer::~EditorBuffer() { Cell *cp = start; while (cp != NULL) { Cell *next = cp->link; delete cp; cp = next; } List-Based Buffer Implementation

/* * Implementation notes: EditorBuffer destructor * * The destructor must delete every cell in the buffer. Note that the loop * structure is not exactly the standard for loop pattern for processing * every cell within a linked list. The complication that forces this * change is that the body of the loop can't free the current cell and * later have the for loop use the link field of that cell to move to * the next one. To avoid this problem, this implementation copies the * link pointer before calling delete. */ EditorBuffer::~EditorBuffer() { Cell *cp = start; while (cp != NULL) { Cell *next = cp->link; delete cp; cp = next; } void EditorBuffer::moveCursorForward() { if (cursor->link != NULL) { cursor = cursor->link; } void EditorBuffer::moveCursorBackward() { Cell *cp = start; if (cursor != start) { while (cp->link != cursor) { cp = cp->link; } cursor = cp; } void EditorBuffer::moveCursorToStart() { cursor = start; } void EditorBuffer::moveCursorToEnd() { while (cursor->link != NULL) { moveCursorForward(); } List-Based Buffer Implementation

void EditorBuffer::moveCursorForward() { if (cursor->link != NULL) { cursor = cursor->link; } void EditorBuffer::moveCursorBackward() { Cell *cp = start; if (cursor != start) { while (cp->link != cursor) { cp = cp->link; } cursor = cp; } void EditorBuffer::moveCursorToStart() { cursor = start; } void EditorBuffer::moveCursorToEnd() { while (cursor->link != NULL) { moveCursorForward(); } /* * Implementation notes: insertCharacter, deleteCharacter * * The primary advantage of the linked list representation for * the buffer is that the insert and delete operations can be * performed in constant time by updating pointers instead of * moving data. */ void EditorBuffer::insertCharacter(char ch) { Cell *cp = new Cell; cp->ch = ch; cp->link = cursor->link; cursor->link = cp; cursor = cp; } void EditorBuffer::deleteCharacter() { if (cursor->link != NULL) { Cell *oldcell = cursor->link; cursor->link = oldcell->link; delete oldcell; } List-Based Buffer Implementation

Complexity of the Editor Operations F moveCursorForward() O(1) B moveCursorBackward() O(1) O(N)O(N) J moveCursorToStart() O(1)O(N)O(N) Z moveCursorToEnd() O(1)O(N)O(N)O(N)O(N) I insertCharacter(ch) O(N)O(N)O(1) D deleteCharacter() O(N)O(N)O(1) arraystacklist Is it possible to reimplement the editor buffer so that all six of these operations run in constant time?Is it possible to reimplement the editor buffer so that all six of these operations run in constant time? The answer is yes, and you will have the opportunity to write the necessary code for next week’s section.The answer is yes, and you will have the opportunity to write the necessary code for next week’s section.

The End