1 Chapter 3 Arrays, Linked Lists, and Recursion. 2 Static vs. Dynamic Structures A static data structure has a fixed size This meaning is different than.

Slides:



Advertisements
Similar presentations
Chapter 22 Implementing lists: linked implementations.
Advertisements

Chapter 4 Linked Lists. © 2005 Pearson Addison-Wesley. All rights reserved4-2 Preliminaries Options for implementing an ADT List –Array has a fixed size.
Linked Lists Chapter 4.
CHP-5 LinkedList.
© 2006 Pearson Addison-Wesley. All rights reserved5 A-1 Chapter 5 Linked Lists CS102 Sections 51 and 52 Marc Smith and Jim Ten Eyck Spring 2008.
Lists and the Collections Framework
Comparison summary Array based (dynamic) Keeps place for up to 4N elements Each element takes 1 memory places Fast accession time Slow removals and insertion.
Linked Lists. Preliminaries Options for implementing an ADT List Array Has a fixed size Data must be shifted during insertions and deletions Dynamic array.
1 Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  Chapter 11 of the book.
Chapter 10 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Explain the underlying concepts of recursion.
© 2006 Pearson Addison-Wesley. All rights reserved5 A-1 Chapter 5 Linked Lists.
Linked Lists part II. Linked Lists A linked list is a dynamic data structure consisting of nodes and links: 627 start 8 This symbol indicates a null reference.
Chapter 4 Linked Lists. © 2005 Pearson Addison-Wesley. All rights reserved4-2 Preliminaries Options for implementing an ADT List –Array has a fixed size.
ELC 310 Day 24. © 2004 Pearson Addison-Wesley. All rights reserved11-2 Agenda Questions? Problem set 5 Parts A Corrected  Good results Problem set 5.
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Odds and Ends Strings (from Chapter 9) StringTokenizer.
Chapter 3: Arrays, Linked Lists, and Recursion
CHAPTER 10 Recursion. 2 Recursive Thinking Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
Linking Objects Together References are particularly important in computer science because they make it possible to represent the relationship among objects.
Chapter 11 Recursion. © 2004 Pearson Addison-Wesley. All rights reserved11-2 Recursion Recursion is a fundamental programming technique that can provide.
Chapter 4 Linked Lists. © 2005 Pearson Addison-Wesley. All rights reserved4-2 Preliminaries Options for implementing an ADT List –Array has a fixed size.
Recursion Chapter 5.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
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.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 4: Linked Lists Data Abstraction & Problem Solving with.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
CSE 501N Fall ‘09 12: Recursion and Recursive Algorithms 8 October 2009 Nick Leidenfrost.
11-1 Recursive Thinking A recursive definition is one which uses the word or concept being defined in the definition itself When defining an English word,
Lists II. List ADT When using an array-based implementation of the List ADT we encounter two problems; 1. Overflow 2. Wasted Space These limitations are.
Lecture 7 b Recursion is a fundamental programming technique that can provide an elegant solution to certain kinds of problems b Today: thinking in a recursive.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 8: Recursion Presentation slides for Java Software Solutions for AP* Computer Science 3rd.
© 2006 Pearson Addison-Wesley. All rights reserved5 B-1 Chapter 5 (continued) Linked Lists.
Data Abstraction and Problem Solving with JAVA Walls and Mirrors Frank M. Carrano and Janet J. Prichard © 2001 Addison Wesley Data Abstraction and Problem.
CS2006- Data Structures I Chapter 5 Linked Lists III.
Linked Lists Chapter 4. Linked Structures: Motivations Arrays have fixed size –Problematic for data structures of arbitrary size Arrays order items physically.
Chapter 5 Linked Lists. © 2004 Pearson Addison-Wesley. All rights reserved 5 A-2 Preliminaries Options for implementing an ADT –Array Has a fixed size.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12 Recursion.
CSC 205 Programming II Lecture 15 Linked List – Other Variations.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Chapter 17: Linked Lists. Objectives In this chapter, you will: – Learn about linked lists – Learn the basic properties of linked lists – Explore insertion.
1 Linked List. Outline Introduction Insertion Description Deletion Description Basic Node Implementation Conclusion.
Given a node v of a doubly linked list, we can easily insert a new node z immediately after v. Specifically, let w the be node following v. We execute.
CC 215 DATA STRUCTURES LINKED LISTS Dr. Manal Helal - Fall 2014 Lecture 3 AASTMT Engineering and Technology College 1.
1 Linked List. List vs Arrays Two built-in data structures that can be used to organize data, or to create other data structures: Lists Arrays.
Data Abstraction and Problem Solving with JAVA Walls and Mirrors Frank M. Carrano and Janet J. Prichard © 2001 Addison Wesley Data Abstraction and Problem.
C++ Programming:. Program Design Including
Chapter 5 Linked Lists © 2006 Pearson Addison-Wesley. All rights reserved.
Linked Lists Chapter 5 (continued)
Data Structure Interview Question and Answers
Chapter 5 Linked Lists © 2011 Pearson Addison-Wesley. All rights reserved.
Chapter 4 Linked Lists.
Data Structures Interview / VIVA Questions and Answers
Chapter 4 Linked Lists
Chapter 4 Linked Lists.
Arrays and Linked Lists
Linked Lists.
Chapter 5 Linked Lists © 2006 Pearson Addison-Wesley. All rights reserved.
Dynamic Data Structures and Generics
Linked Lists Chapter 4.
Chapter 4 Linked Lists.
Linked Lists The items in a linked list data structure are linked to one another An item in a linked list references its successor A linked list is able.
Chapter 11 Recursion.
Figure 4.1 a) A linked list of integers; b) insertion; c) deletion.
Linked Lists Chapter 5 (continued)
Chapter 5 Linked Lists © 2006 Pearson Addison-Wesley. All rights reserved.
Chapter 5 Linked Lists © 2011 Pearson Addison-Wesley. All rights reserved.
Linked Lists Chapter 5 (continued)
Linked Lists Chapter 5 (continued)
Presentation transcript:

1 Chapter 3 Arrays, Linked Lists, and Recursion

2 Static vs. Dynamic Structures A static data structure has a fixed size This meaning is different than those associated with the static modifier Arrays are static; once you define the number of elements it can hold, it doesn’t change A dynamic data structure grows and shrinks as required by the information it contains

3 Preliminaries Options for implementing an ADT Array Array Has a fixed size Data must be shifted during insertions and deletions Linked list Linked list Is able to grow in size as needed Does not require the shifting of items during insertions and deletions

4 Object References Recall that an object reference is a variable that stores the address of an object A reference can also be called a pointer They are often depicted graphically: student John Smith

5 Object References Figure 4.3a-d a) Declaring reference variables; b) allocating an object; c) allocating another object, with the dereferenced object marked for garbage collection

6 References as Links Object references can be used to create links between objects Suppose a Student class contained a reference to another Student object John Smith Jane Jones

7 References as Links References can be used to create a variety of linked structures, such as a linked list: studentList

8 Preliminaries Figure 4.1 a) A linked list of integers; b) insertion; c) deletion

9 Object References An array of objects Is actually an array of references to the objects Is actually an array of references to the objects Example Example Integer[] scores = new Integer[30]; Instantiating Integer objects for each array reference Instantiating Integer objects for each array reference scores[0] = new Integer(7); scores[1] = new Integer(9); // and so on …

10 Object References Equality operators ( == and != ) Compare the values of the reference variables, not the objects that they reference Compare the values of the reference variables, not the objects that they reference equals method Compares objects field by field Compares objects field by field When an object is passed to a method as an argument, the reference to the object is copied to the method’s formal parameter Reference-based ADT implementations and data structures use Java references

11 Resizable Arrays The number of references in a Java array is of fixed size Resizable array An array that grows and shrinks as the program executes An array that grows and shrinks as the program executes An illusion that is created by using an allocate and copy strategy with fixed-size arrays An illusion that is created by using an allocate and copy strategy with fixed-size arrays java.util.Vector class Uses a similar technique to implement a growable array of objects Uses a similar technique to implement a growable array of objects

12 Reference-Based Linked Lists Linked list Contains nodes that are linked to one another Contains nodes that are linked to one another A node A node Contains both data and a “link” to the next item Can be implemented as an object public class Node { private Object item; private Object item; private Node next; private Node next; // constructors, accessors, // constructors, accessors, // and mutators … // and mutators … } // end class Node Figure 4.5 A node

13 Reference-Based Linked Lists Using the Node class Node n = new Node (new Integer(6)); Node first = new Node (new Integer(9), n); Figure 4.7 Using the Node constructor to initialize a data field and a link value

14 Reference-Based Linked Lists Data field next in the last node is set to null head reference variable References the list’s first node References the list’s first node Always exists even when the list is empty Always exists even when the list is empty Figure 4.8 A head reference to a linked list

15 Reference-Based Linked Lists head reference variable can be assigned null without first using new Following sequence results in a lost node Following sequence results in a lost node head = new Node(); // Don’t really need to use new here head = null; // since we lose the new Node object here Figure 4.9 A lost node

16 Programming with Linked Lists: Displaying the Contents of a Linked List curr reference variable References the current node References the current node Initially references the first node Initially references the first node To display the data portion of the current node System.out.println(curr.getItem()); To advance the current position to the next node curr = curr.getNext();

17 Displaying the Contents of a Linked List Figure 4.10 The effect of the assignment curr = curr.getNext( )

18 Displaying the Contents of a Linked List To display all the data items in a linked list for (Node curr = head; curr != null; curr = curr.getNext()) { System.out.println(curr.getItem()); } // end for

19 Deleting a Specified Node from a Linked List To delete node N which curr references Set next in the node that precedes N to reference the node that follows N Set next in the node that precedes N to reference the node that follows Nprev.setNext(curr.getNext()); Figure 4.11 Deleting a node from a linked list

20 Deleting a Specified Node from a Linked List Deleting the first node is a special case head = head.getNext(); Figure 4.12 Deleting the first node

21 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 newNode.setNext(curr);prev.setNext(newNode); Figure 4.13 Inserting a new node into a linked list

22 Inserting a Node into a Specified Position of a Linked List To insert a node at the beginning of a linked list newNode.setNext(head); head = newNode; Figure 4.14 Inserting at the beginning of a linked list

23 Inserting a Node into a Specified Position of a Linked List Inserting at the end of a linked list is not a special case if curr is null newNode.setNext(curr);prev.setNext(newNode); Figure 4.15 Inserting at the end of a linked list

24 Inserting a Node into a Specified Position of a Linked List Three steps to insert a new node into a linked list Determine the point of insertion Determine the point of insertion Create a new node and store the new data in it Create a new node and store the new data in it Connect the new node to the linked list by changing references Connect the new node to the linked list by changing references

25 Determining curr and prev Determining the point of insertion or deletion for a sorted linked list of objects for ( prev = null, curr = head; (curr != null) && (newValue.compareTo(curr.getItem()) > 0); prev = curr, curr = curr.getNext() ) { } // end for

26 A Reference-Based Implementation of the ADT List A reference-based implementation of the ADT list Does not shift items during insertions and deletions Does not shift items during insertions and deletions Does not impose a fixed maximum length on the list Does not impose a fixed maximum length on the list Figure 4.18 A reference-based implementation of the ADT list

27 Comparing Array-Based and Referenced-Based Implementations Size Array-based Array-based Fixed size Issues Issues Can you predict the maximum number of items in the ADT? Will an array waste storage? Resizable array Resizable array Increasing the size of a resizable array can waste storage and time

28 Comparing Array-Based and Referenced-Based Implementations Size (Continued) Reference-based Reference-based Do not have a fixed size Do not need to predict the maximum size of the list Do not need to predict the maximum size of the list Will not waste storage Will not waste storage Storage requirements Array-based Array-based Requires less memory than a reference-based implementation There is no need to store explicitly information about where to find the next data item There is no need to store explicitly information about where to find the next data item

29 Comparing Array-Based and Referenced-Based Implementations Storage requirements (Continued) Reference-based Reference-based Requires more storage An item explicitly references the next item in the list An item explicitly references the next item in the list Access time Array-based Array-based Constant access time Reference-based Reference-based The time to access the i th node depends on i

30 Comparing Array-Based and Referenced-Based Implementations Insertion and deletions Array-based Array-based Require you to shift the data Reference-based Reference-based Do not require you to shift the data Require a list traversal

31 Passing a Linked List to a Method A method with access to a linked list’s head reference has access to the entire list When head is an actual argument to a method, its value is copied into the corresponding formal parameter Figure 4.19 A head reference as an argument

32 Processing Linked List Recursively Traversal Recursive strategy to display a list Recursive strategy to display a list Write the first node of the list Write the list minus its first node Recursive strategies to display a list backward Recursive strategies to display a list backward writeListBackward strategy Write the last node of the list Write the list minus its last node backward writeListBackward2 strategy Write the list minus its first node backward Write the first node of the list

33 Processing Linked List Recursively Insertion Recursive view of a sorted linked list Recursive view of a sorted linked list The linked list that head references is a sorted linked list if head is null (the empty list is a sorted linked list) or head.getNext() is null (a list with a single node is a sorted linked list) or head.getItem() < head.getNext().getItem(), and head.getNext() references a sorted linked list

34 Variations of the Linked List: Tail References tail reference Remembers where the end of the linked list is Remembers where the end of the linked list is To add a node to the end of a linked list To add a node to the end of a linked list tail.setNext(new Node(request, null)); Figure 4.22 A linked list with head and tail references

35 Circular Linked List Last node references the first node Every node has a successor Figure 4.23 A circular linked list

36 Circular Linked List Figure 4.24 A circular linked list with an external reference to the last node

37 Doubly Linked List Each node references both its predecessor and its successor Figure 4.27 A doubly linked list

38 Doubly Linked List Circular doubly linked list precede reference of the head node references the last node precede reference of the head node references the last node next reference of the last node references the head node next reference of the last node references the head node Eliminates special cases for insertions and deletions Eliminates special cases for insertions and deletions

39 Doubly Linked List To delete the node that curr references curr.getPrecede().setNext(curr.getNext());curr.getNext().setPrecede(curr.getPrecede()); Figure 4.29 Reference changes for deletion

40 Doubly Linked List To insert a new node that newNode references before the node referenced by curr newNode.setNext(curr);newNode.setPrecede(curr.getPrecede());curr.setPrecede(newNode);newNode.getPrecede().setNext(newNode); Figure 4.30 Reference changes for insertion

41 Summary Reference variables can be used to implement the data structure known as a linked list Each reference in a linked list is a reference to the next node in the list Algorithms for insertions and deletions in a linked list involve Traversing the list from the beginning until you reach the appropriate position Traversing the list from the beginning until you reach the appropriate position Performing reference changes to alter the structure of the list Performing reference changes to alter the structure of the list

42 Summary Inserting a new node at the beginning of a linked list and deleting the first node of a linked list are special cases An array-based implementation uses an implicit ordering scheme; a reference-based implementation uses an explicit ordering scheme Any element in an array can be accessed directly; you must traverse a linked list to access a particular node Items can be inserted into and deleted from a reference-based linked list without shifting data

43 Summary The new operator can be used to allocate memory dynamically for both an array and a linked list The size of a linked list can be increased one node at a time more efficiently than that of an array The size of a linked list can be increased one node at a time more efficiently than that of an array A binary search of a linked list is impractical Recursion can be used to perform operations on a linked list The recursive insertion algorithm for a sorted linked list works because each smaller linked list is also sorted

44 Summary A tail reference can be used to facilitate locating the end of a list In a circular linked list, the last node references the first node Dummy head nodes eliminate the special cases for insertion into and deletion from the beginning of a linked list A head record contains global information about a linked list A doubly linked list allows you to traverse the list in either direction

45 Recursive Thinking A recursive definition is one which uses the word or concept being defined in the definition itself When defining an English word, a recursive definition is often not helpful – “When a person is hungry it means they are hungry”. But in other situations, a recursive definition can be an appropriate way to express a concept

46 Recursive Definitions Consider the following list of numbers: 24, 88, 40, 37 Such a list can be defined as A LIST is a: number A LIST is a: number or a: number comma LIST or a: number comma LIST That is, a LIST is defined to be a single number, or a number followed by a comma followed by a LIST The concept of a LIST is used to define itself

47 Infinite Recursion All recursive definitions MUST have a non- recursive part Otherwise you’d get infinite recursion The non-recursive part is often called the base case A LIST (of numbers) is defined to be: a: number(base case) or or a: number comma LIST(recursive part)

48 Recursive Programming A method in Java can invoke itself; if it does then it is called a recursive method If a method does invoke itself, at some point its got to stop it! Otherwise it will invoke itself “forever”! The end result of infinite recursion is that your program will run out of memory. Even though the method is invoking itself, the local (method) data associated with each invocation is unique. As always, when the method completes, control returns to the method that invoked it (which may be an earlier invocation of itself)

49 Indirect Recursion A method invoking itself is considered to be direct recursion A method could invoke another method, which invokes another, etc., until eventually the original method is invoked again For example, method m1 could invoke m2, which invokes m3, which in turn invokes m1 again This is called indirect recursion, and requires all the same care as direct recursion It is often more difficult to trace and debug

50 Indirect Recursion m1m2m3 m1m2m3 m1m2m3

51 Recursive Programming Just because we can use recursion to solve a problem, it doesn't mean we should. For instance, we usually would not use recursion to solve the sum of 1 to N problem, because the iterative version is easier to understand There are other reasons to NOT use recursion – efficiency (time, space) being one of the big ones. General rule: recursion is slower (sometimes much slower, or “dog slow” in programmer vernacular) than a well-coded iterative approach. However, for some problems, recursion provides an elegant solution, often cleaner than an iterative version You must carefully decide whether recursion is the correct technique for any problem One of the most important elements to consider is the MAXIMUM expected stack depth

52