LINKED DATA STRUCTURES



Similar documents
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

DATA STRUCTURES USING C

10CS35: Data Structures Using C

Algorithms and Data Structures Written Exam Proposed SOLUTION

22c:31 Algorithms. Ch3: Data Structures. Hantao Zhang Computer Science Department

Lecture 12 Doubly Linked Lists (with Recursion)

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

Binary Heap Algorithms

Analysis of a Search Algorithm

- 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

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

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

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

D06 PROGRAMMING with JAVA

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

ADTs,, Arrays, Linked Lists

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:

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

Data Structures and Algorithms Lists

PES Institute of Technology-BSC QUESTION BANK

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

Linked Lists Linked Lists, Queues, and Stacks

CSE 2123 Collections: Sets and Iterators (Hash functions and Trees) Jeremy Morris

Lecture 1: Data Storage & Index

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

AP Computer Science AB Syllabus 1

Project 4 DB A Simple database program

7.1 Our Current Model

Sequential Data Structures

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

Chapter 8: Bags and Sets

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

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

Data Structures and Algorithms

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.

CHAPTER 4 ESSENTIAL DATA STRUCTRURES

Zabin Visram Room CS115 CS126 Searching. Binary Search

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

ECE 250 Data Structures and Algorithms MIDTERM EXAMINATION /5:15-6:45 REC-200, EVI-350, RCH-106, HH-139

dictionary find definition word definition book index find relevant pages term list of page numbers

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

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

Moving from CS 61A Scheme to CS 61B Java

Node-Based Structures Linked Lists: Implementation

1. What are Data Structures? Introduction to Data Structures. 2. What will we Study? CITS2200 Data Structures and Algorithms

STACKS,QUEUES, AND LINKED LISTS

Unit Storage Structures 1. Storage Structures. Unit 4.3

Ordered Lists and Binary Trees

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

Unordered Linked Lists

Data Structure with C

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team

Data Structures. Level 6 C Module Descriptor

Memory Allocation. Static Allocation. Dynamic Allocation. Memory Management. Dynamic Allocation. Dynamic Storage Allocation

Glossary of Object Oriented Terms

Software Engineering Techniques

cs2010: algorithms and data structures

Krishna Institute of Engineering & Technology, Ghaziabad Department of Computer Application MCA-213 : DATA STRUCTURES USING C

What is a Stack? Stacks and Queues. Stack Abstract Data Type. Java Interface for Stack ADT. Array-based Implementation

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

CS 111 Classes I 1. Software Organization View to this point:

Introduction to Programming System Design. CSCI 455x (4 Units)

Lecture Notes on Binary Search Trees

Common Data Structures

Linked List as an ADT (cont d.)

Arrays. Introduction. Chapter 7

Chapter 13. Disk Storage, Basic File Structures, and Hashing

Dynamic programming formulation

Data storage Tree indexes

INTERNATIONAL JOURNAL OF PURE AND APPLIED RESEARCH IN ENGINEERING AND TECHNOLOGY

Classes: Relationships Among Objects. Atul Prakash Background readings: Chapters 8-11 (Downey)

Organization of Programming Languages CS320/520N. Lecture 05. Razvan C. Bunescu School of Electrical Engineering and Computer Science

CMSC 202H. ArrayList, Multidimensional Arrays

Data Structures and Algorithms Written Examination

CSE373: Data Structures and Algorithms Lecture 3: Math Review; Algorithm Analysis. Linda Shapiro Winter 2015

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

Copyright 2007 Ramez Elmasri and Shamkant B. Navathe. Slide 13-1

Java Program Coding Standards Programming for Information Technology

Introduction to Data Structures

language 1 (source) compiler language 2 (target) Figure 1: Compiling a program

A binary heap is a complete binary tree, where each node has a higher priority than its children. This is called heap-order property

Interactive Applications (CLI) and Math

Hash Tables. Computer Science E-119 Harvard Extension School Fall 2012 David G. Sullivan, Ph.D. Data Dictionary Revisited

root node level: internal node edge leaf node Data Structures & Algorithms McQuain

Universidad Carlos III de Madrid

The following themes form the major topics of this chapter: The terms and concepts related to trees (Section 5.2).

Binary Heaps. CSE 373 Data Structures

Binary Search Trees. A Generic Tree. Binary Trees. Nodes in a binary search tree ( B-S-T) are of the form. P parent. Key. Satellite data L R

Chapter 7: Sequential Data Structures

This lecture. Abstract data types Stacks Queues. ADTs, Stacks, Queues Goodrich, Tamassia

AP Computer Science Java Mr. Clausen Program 9A, 9B

Data Structures and Algorithms

STORM. Simulation TOol for Real-time Multiprocessor scheduling. Designer Guide V3.3.1 September 2009

Physical Data Organization

Abstract Data Types. Chapter 2

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

GDB Tutorial. A Walkthrough with Examples. CMSC Spring Last modified March 22, GDB Tutorial

Transcription:

LINKED DATA STRUCTURES 1

Linked Lists A linked list is a structure in which objects refer to the same kind of object, and where: the objects, called nodes, are linked in a linear sequence. we keep a reference to the first node of the list (called the front or head ). The nodes are used to store data. For example, here is a class for nodes in a linked list of ints: public class IntNode { public int value; public IntNode link; public IntNode(int v) { value = v; Note: having public instance variables is not as bad here as it might first look. Why? Drawing a linked list The next slide shows in detail how memory might look for a linked list containing 5 nodes. 2

Static area not of interest in this example. Assume we have a class LExample whose main builds a linked list for front to refer to. main:9 LExample xae IntNode int value 98 IntNode link null x7f IntNode int value 161 IntNode link xae IntNode front x88 x57 IntNode xd0 IntNode int value 5 int value 14 IntNode link x7f IntNode link x57 x88 IntNode int value -31 IntNode link xd0 3

A simpler picture front 31 5 161 14 98 When drawing such diagrams, always be careful to anchor the references clearly, i.e., to show where they are stored. Note that there are several conventions for drawing a null reference, including: Preferred: Not as nice: 4

Tracing It s easy for linked structures to get all tangled up, so you will have to develop some new debugging skills for working with them. When writing, debugging, or understanding code with linked structures, it is extremely useful to trace by hand, using diagrams. Exercise: Trace this code. public class Example { public static void main(string[] args) { // Make a variable to refer to the list, // and put one element into the list. IntNode front = new IntNode(95); // Put another element into the list IntNode temp = new IntNode(104); temp.link = front; front = temp; // We can chain together dots: System.out.println(front.link.value); // 95 5

Questions and Exercises What happens if we repeat the 3 lines Put another... several times, using a different integer each time? Suppose you want to write a general method that inserts a new element at the front of a linked list of IntNodes, for use in the example code. What header would you use? Have you considered the case where the list is empty? Write your insert method. Write a general method that prints out the contents of a linked list of IntNodes. Write a test driver for your two methods and use it to test them. Think up other methods to practice using linked lists. 6

Hints for working with linked structures Trace your code by hand, using pictures, as you write it. If you are ever unsure of what some code does to references, make up fake memory addresses for the references and treat them like ordinary integers. Every time you write a line like this: blah.bloop to follow a reference, be sure the reference (in this case blah) is not null. Either (1) use an if, or (2) be sure that the reference cannot possibly be null in that context, and assert that fact in a comment. 7

Arrays are contiguous Linked Lists vs Arrays In an array, the elements have to be in a contiguous (connected and sequential) portion of memory. Memory immediately next to the array may already be in use for something else. So programming languages don t generally provide for arrays that can grow and shrink in place. Question: Doesn t Java s ArrayList do just that? Linked lists are not contiguous In a linked list, the reference in each node says where to find the next one. So the nodes can be all over memory. 8

Implications With an array, we must choose a size once and for all. (This can waste memory, or we could run out of spaces). With a linked list, we can add and remove elements at will. (Each one does take up a little more space for its link field, and it may take time to get to the insertion / removal spot). With an array, we can immediately access the n th element. With a linked list, we cannot. We have to follow n pointers. 9

Which is better? Neither arrays nor linked lists are best; it depends on what you re going to do most (e.g., search or update?), and what your priorities are (e.g., time or space?). Java also takes time managing the location of objects in memory. It has to find an empty range of memory when we construct a new object. And it looks for unreferenced objects, to reuse their memory. But this is outside the scope of our course. 10

Deletion from a Linked List Question: If the list is sorted, should we use binary search to find the element to delete? Unlike an array, there is no need to shift any elements up to fill the hole left by deletion. We just unlink the unwanted element. front 31 5 161 14 98 11

Implementing the queue ADT: Deletion /** A node in a linked list. */ class ListNode { public Object value; public ListNode link; /** A ListNode containing o. */ public ListNode(Object o) { value = o; /** Note: elements are compared by equals(object). */ interface ExtendedQueue extends Queue { /** Return whether I contain o. */ public abstract boolean contains(object o); /** Remove first (starting from the front) * occurrence of o from me if it s there. */ public abstract void delete(object o); public class LinkedQueue implements ExtendedQueue { /** Front node in my linked list. */ private ListNode front; // Methods go here. See next slide for delete. 12

Method details /** Remove first (starting from the front) * occurrence of o from me if it s there. */ public void delete(object o) { ListNode previous = null; ListNode current = front; // Follow links until we fall off, or until we // find the node to delete. while (current!= null &&! current.value.equals(o)) { previous = current; current = current.link; // If we didn t fall off, we found it. // Update either the front of the list or the previous link. if (current!= null) { if (current == front) { front = current.link; else { previous.link = current.link; 13

Questions: Why did we initialize previous? When implementing Queue with a linked list, should we keep a pointer to the end of the linked list? What about when implementing Stack? Exercises: Devise a thorough set of test cases for delete. Modify delete so that it handles null elements. In delete, previous is used to pass information from one iteration to the next: it remembers information from the previous iteration. Write delete using only one local variable, by looking ahead. Implement all Queue methods in LinkedQueue. Trace the code by hand for each method. 14

Other Linked Data Structures References can be used to create many different data structures. Circularly-linked lists front apple bee honey wasp tree The last element contains a reference to the first element, rather than null. 15

Doubly-linked lists Each element keeps both a frontwards and a backwards reference. front ace by hi /** A node for a doubly linked list of Strings. */ class DoubleNode { public String value; public DoubleNode next, prev; /** A DoubleNode containing v. */ public DoubleNode(String v) { value = v; This could be useful for a list presented on screen, so we can easily write code to scroll up and down. 16

When traversing a doubly-linked list to prepare for insertion or deletion, there is no need to use both a current and previous reference: each node has a built-in reference to the previous element. Deletion with a doubly-linked list: front deleterecord ace by hi Insertion with a doubly-linked list: front insertbefore ace by hi apple newrecord 17

Exercise: Write complete insertion and deletion methods for a sorted doublylinked list. /** Insert a new node containing s into the appropriate * position in the sorted, doubly-linked list whose * first node is front. * Return the (possibly new) first node. */ public static DoubleNode insert(doublenode front, String s) /** Delete s, if it exists, from the doubly-linked list * whose first node is front. * Return the (possibly new) first node. */ public static DoubleNode delete(doublenode front, String s) Questions: The above comments aren t clear about the behaviour in certain circumstances. What are those circumstances? Why do we make these methods static? Exercise: Think about the pros and cons of using a doubly-linked list of Comparables instead of Strings. 18