CENG 218 Classes and Data Structures

Slides:



Advertisements
Similar presentations
DATA STRUCTURES USING C++ Chapter 5
Advertisements

Review Learn about linked lists
An Array-Based Implementation of the ADT List public class ListArrayBased implements ListInterface { private static final int MAX_LIST = 50; private Object.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 17: Linked Lists.
Chapter 3: Arrays, Linked Lists, and Recursion
Data Structures Using C++ 2E
11 Values and References Chapter Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 8 Stacks and Queues Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
Stacks & Recursion. Stack pushpop LIFO list - only top element is visible top.
C++ Classes and Data Structures Jeffrey S. Childs
1 CSC 222: Computer Programming II Spring 2004 Pointers and linked lists  human chain analogy  linked lists: adding/deleting/traversing nodes  Node.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 13 Recursion Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
Arrays Tonga Institute of Higher Education. Introduction An array is a data structure Definitions  Cell/Element – A box in which you can enter a piece.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 14 Introduction to Sorting Algorithms Jeffrey S. Childs Clarion University of PA © 2008, Prentice.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 5 An Array Class Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
1 Chapter 7 Stacks and Queues. 2 Stack ADT Recall that ADT is abstract data type, a set of data and a set of operations that act upon the data. In a stack,
Pointers OVERVIEW.
Linked Lists part 2 CS 244 Brent M. Dingle, Ph.D. Game Design and Development Program Department of Mathematics, Statistics, and Computer Science University.
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.
1 Chapter 7 The Linked List as a Data Structure. 2 The List ADT A list is a list of elements. The list of elements consist of the data acted upon by list.
C++ Classes and Data Structures Jeffrey S. Childs
Dynamic Array. An Array-Based Implementation - Summary Good things:  Fast, random access of elements  Very memory efficient, very little memory is required.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 11 Hash Tables Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 15 Other Data Structures Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
Linked lists. Data structures to store a collection of items Data structures to store a collection of items are commonly used Typical operations on such.
1 Chapter 6 Methods for Making Data Structures. 2 Dynamic Arrays in Data Structures In almost every data structure, we want functions for inserting and.
Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
An Array-Based Implementation of the ADT List
Memory Management.
Chapter 16: Linked Lists.
Linked Lists.
Lecture 6 of Computer Science II
Review Array Array Elements Accessing array elements
C++ Programming:. Program Design Including
Winter 2009 Tutorial #6 Arrays Part 2, Structures, Debugger
Pointers and Linked Lists
Pointers and Linked Lists
C++ Classes and Data Structures Jeffrey S. Childs
Review Deleting an Element from a Linked List Deletion involves:
Data Structure and Algorithms
Doubly Linked List Review - We are writing this code
Linked lists.
Queues Queues Queues.
Linked Lists head One downside of arrays is that they have a fixed size. To solve this problem of fixed size, we’ll relax the constraint that the.
CSCI 3333 Data Structures Linked Lists.
LINKED LISTS CSCD Linked Lists.
Pointers and Dynamic Variables
Top Ten Words that Almost Rhyme with “Peas”
Prof. Neary Adapted from slides by Dr. Katherine Gibson
Introduction to Linked Lists
CMSC 341 Lecture 10 B-Trees Based on slides from Dr. Katherine Gibson.
Linked Lists.
C++ Classes and Data Structures Jeffrey S. Childs
Arrays and Linked Lists
B- Trees D. Frey with apologies to Tom Anastasio
Linked Lists.
B- Trees D. Frey with apologies to Tom Anastasio
Linked List.
B- Trees D. Frey with apologies to Tom Anastasio
Data Structures Sorted Arrays
Lists.
Stacks, Queues, and Deques
Lists CMSC 202, Version 4/02.
slides created by Ethan Apter
Linked lists.
Classes and Objects Object Creation
CMSC 202 Constructors Version 9/10.
Data Structures & Programming
Presentation transcript:

CENG 218 Classes and Data Structures

Dynamic Arrays in Data Structures In the class for a data structure, we can add an Array object to the private section to store data The functions of the data structure can expand or shrink the Array to conserve memory – this relieves the client from thinking about doing this

Dynamic Arrays in Data Structures (cont.) In almost every data structure, we want functions for inserting and removing data When dynamic arrays are used, the insertion function would add data to the array, while the removal function would “eliminate” data from the array (make it unusable) When the array becomes full, we would want to do an expansion – when many elements have been removed, we would want to do a contraction, so that only the used elements remain

Array Expansion/Contraction One possible method: When an element is inserted by the client, increase the size of the array by 1 When an element is removed by the client, decrease the size of the array by 1 The problem with this method is that it is inefficient – every time an element is inserted or removed, the changeSize function is called…

changeSize Function 33 0 1 2 3 432 433 444 445 … 25 75 10 12 56 32 73 87 New element needs to be put into array, so changeSize function is called

changeSize Function (cont.) 0 1 2 3 432 433 444 445 … 25 75 10 12 56 32 73 87 0 1 2 3 432 433 444 445 446 … new array is made

changeSize Function (cont.) 0 1 2 3 432 433 444 445 … 25 75 10 12 56 32 73 87 0 1 2 3 432 433 444 445 446 … 25 75 10 12 56 32 73 87 elements are copied over one by one using a for loop

changeSize Function (cont.) 33 0 1 2 3 432 433 444 445 446 … 25 75 10 12 56 32 73 87 33 Then, the new element can be put in

changeSize Function (cont.) 0 1 2 3 432 433 444 445 446 … 25 75 10 12 56 32 73 87 33 This process would take place every time a new element needs to be inserted.

changeSize Function (cont.) 0 1 2 3 432 433 444 445 446 … 25 75 10 12 56 32 73 87 33 Likewise, when an element needs to be removed, this method contracts the array by one to conserve memory.

changeSize Function (cont.) 0 1 2 3 432 433 444 445 446 … 25 75 10 12 56 32 73 87 33 Suppose the element at the end of the array needs to be removed.

changeSize Function (cont.) 0 1 2 3 432 433 444 445 446 … 25 75 10 12 56 32 73 87 33 0 1 2 3 432 433 444 445 … The changeSize function is called and a new, smaller array is made.

changeSize Function (cont.) 0 1 2 3 432 433 444 445 446 … 25 75 10 12 56 32 73 87 33 0 1 2 3 432 433 444 445 … 25 75 10 12 56 32 73 87 The elements are copied over one by one, using a for loop.

changeSize Function (cont.) 0 1 2 3 432 433 444 445 … 25 75 10 12 56 32 73 87 This method of array expansion/contraction is largely inefficient, because there is too much element copying.

A Better Method When the Array is full, double the size of it When the number of elements used in the Array falls to 25% of the Array’s capacity, cut the size of the Array in half (it will be half full after the cut)

A Better Method (cont.) 0 1 2 3 25 75

A Better Method (cont.) 0 1 2 3 25 75 10

A Better Method (cont.) 0 1 2 3 25 75 10 12

A Better Method (cont.) 0 1 2 3 33 25 75 10 12 Array is full, so call changeSize function to double the size.

A Better Method (cont.) 0 1 2 3 4 5 6 7 25 75 10 12 33

A Better Method (cont.) 0 1 2 3 4 5 6 7 25 75 10 12 33 49 29 87 This array is full, but if we removed elements (made them inaccessible), we would cut the size of the array in half when its utilization drops to 25%

A Better Method (cont.) 0 1 2 3 4 5 6 7 25 75 10 12 33 49 29

A Better Method (cont.) 0 1 2 3 4 5 6 7 25 75 10 12 33 49

A Better Method (cont.) 0 1 2 3 4 5 6 7 25 75 10 12 33

A Better Method (cont.) 0 1 2 3 4 5 6 7 25 75 10 12

A Better Method (cont.) 0 1 2 3 4 5 6 7 25 75 10

A Better Method (cont.) 0 1 2 3 4 5 6 7 25 75 Array is 25% utilized, so use changeSize function to cut the size of the array in half.

A Better Method (cont.) 0 1 2 3 25 75 Array is 25% utilized, so use changeSize function to cut the size of the array in half.

A Better Method (cont.) 0 1 2 3 25 75 Using this method, memory is still conserved. There is element copying every time changeSize is called, but it isn’t bad.

A Better Method (cont.) 0 1 2 3 25 75 It can be proven that, on average, there are no more than a couple of elements being copied on each insertion/deletion with this method.

Linked Structures In a data structure, data is not always stored in an Array object Sometimes it is best to store data in a linked structure (an alternative to an Array) A linked structure consists of a group of nodes – each node is made from a struct. An object of the Node struct contains an element of data.

A Node Class Template public class Node<T> { private T data; The info member is for the data. It can anything (T), but it is often the object of another type, used as a record of information. public class Node<T> { private T data; private Node<T> next; //public getters and setters public Node(T inf){ next=null; data=inf; }

A Node Struct Template (cont.) public class Node<T> { private T data; private Node<T> next; //public getters and setters public Node(T inf){ next=null; data=inf; } The next reference(pointer) stores the address of a Node of the same type! This means that each node can point to another node. data next

Nodes In a data structure, each node is made in the heap; therefore, a node can only be accessed by a reference(pointer). The client does not deal with nodes. When the client uses an insertion function, an element of data is passed into the function, and the function places it in a node.

Nodes (cont.) When the client wants to retrieve data, the data in a node is returned to the client (but not the node itself). The node struct template exists for use by the data structure.

Example of a Linked Structure head each node is divided into two sections, for the two members of the Node.

Example of a Linked Structure (cont.) head The left section is the data member.

Example of a Linked Structure (cont.) head The right section is the reference(pointer)(or reference) called “next”.

Example of a Linked Structure (cont.) head The head reference(pointer) would be saved in the private section of a data structure class.

Example of a Linked Structure (cont.) head The last node doesn’t point to another node, so its reference(pointer) (called next) is set to null (indicated by slash).

Linked Lists The arrangement of nodes in the linked structure on the previous slide is often called a linked list. We can access any element of the linked list, for retrieval of information. We can also remove any element from the linked list (which would shorten the list). We can also insert any element into any position in the linked list.

Linked List Advantages Assume we have a list 100,000 elements … … 5 3 7 2 1 Removing an element from the middle of a linked list is fast.

Linked List Advantages (cont.) … … 5 3 2 1 7 Removing an element from the middle of a linked list is fast.

Linked List Advantages (cont.) Assume we have an array having 100,000 elements 211 212 213 214 215 216 217 218 … … 25 75 10 12 33 49 29 87 Removing elements from the middle of an array (without leaving gaps) is more problematic.

Linked List Advantages (cont.) Assume we have an array having 100,000 elements 211 212 213 214 215 216 217 218 … … 25 75 10 33 49 29 87 Removing elements from the middle of an array (without leaving gaps) is more problematic.

Linked List Advantages (cont.) Assume we have an array having 100,000 elements 211 212 213 214 215 216 217 218 … … 25 75 10 33 49 29 87 A loop must be used to slide each element on the right one slot to the left, one at a time…

Linked List Advantages (cont.) Assume we have an array having 100,000 elements 211 212 213 214 215 216 217 218 … … 25 75 10 33 49 29 87

Linked List Advantages (cont.) Assume we have an array having 100,000 elements 211 212 213 214 215 216 217 218 … … 25 75 10 33 49 29 87

Linked List Advantages (cont.) Assume we have an array having 100,000 elements 211 212 213 214 215 216 217 218 … … 25 75 10 33 49 29 87

Linked List Advantages (cont.) Assume we have an array having 100,000 elements 211 212 213 214 215 216 217 218 … … 25 75 10 33 49 29 87

Linked List Advantages (cont.) Assume we have an array having 100,000 elements 211 212 213 214 215 216 217 218 … … 25 75 10 33 49 29 87 Only 100,000 more to go!

Linked List Advantages (cont.) Linked lists also waste less memory for large elements (records of information). Wasted memory is memory space in the data structure not used for data. In arrays, the wasted memory is the part of the array not being utilized. In linked lists, the wasted memory is the reference(pointer) in each node.

Linked List Advantages (cont.) head Linked List Array

Accessing info head To access the info in the first node: head.getData()

Accessing info (cont.) head To access the info in the second node: head.getLink().getData()

Finding the Mercedes head … Mercedes Consider a linked list, where the info member (left half of blue box) is a CarType object We wish to find a Mercedes stored in one of the objects.

CarType Class public class CarType { private double price; private int year; private String maker; public CarType(double price, int year, String maker) { this.price = price; this.year = year; this.maker = maker; } public double getPrice() { return price; public void setPrice(double price) { public int getYear() { return year; public void setYear(int year) { public String getMaker() { return maker; public void setMaker(String maker) { @Override public String toString() { return "CarType [price=" + price + ", year=" + year + ", maker=" + maker + "]"; public boolean equals(Object arg0) { if(arg0!=null){ if(arg0 instanceof CarType){ CarType other=(CarType)arg0; return maker.equals(other.maker); return false;

Finding the Mercedes (cont.) head … Mercedes CarType item=new CarType(…….); item.setMaker(“Mercedes”); Node<CarType> walk = head; while ( ! walk.getData().equals(item ) ) walk=walk.getLink();

Finding the Mercedes (cont.) head … Mercedes CarType item=new CarType(…….); item.setMaker(“Mercedes”); Node<CarType> walk = head; while ( ! walk.getData().equals(item ) ) walk=walk.getLink();

Finding the Mercedes (cont.) head item maker: price: year: … Mercedes CarType item=new CarType(…….); item.setMaker(“Mercedes”); Node<CarType> walk = head; while ( ! walk.getData().equals(item ) ) walk=walk.getLink();

Finding the Mercedes (cont.) item head maker: Mercedes price: year: … Mercedes CarType item=new CarType(…….); item.setMaker(“Mercedes”); Node<CarType> walk = head; while ( ! walk.getData().equals(item ) ) walk=walk.getLink();

Finding the Mercedes (cont.) head item maker: Mercedes price: year: … Mercedes CarType item=new CarType(…….); item.setMaker(“Mercedes”); Node<CarType> walk = head; while ( ! walk.getData().equals(item ) ) walk=walk.getLink();

Finding the Mercedes (cont.) head walk item maker: Mercedes price: year: … Mercedes CarType item=new CarType(…….); item.setMaker(“Mercedes”); Node<CarType> walk = head; while ( ! walk.getData().equals(item ) ) walk=walk.getLink();

Finding the Mercedes (cont.) head walk item maker: Mercedes price: year: … Mercedes CarType item=new CarType(…….); item.setMaker(“Mercedes”); Node<CarType> walk = head; while ( ! walk.getData().equals(item ) ) walk=walk.getLink();

Finding the Mercedes (cont.) head walk item maker: Mercedes price: year: … Mercedes CarType item=new CarType(…….); item.setMaker(“Mercedes”); Node<CarType> walk = head; while ( ! walk.getData().equals(item ) ) walk=walk.getLink();

Finding the Mercedes (cont.) head walk item maker: Mercedes price: year: … Mercedes CarType item=new CarType(…….); item.setMaker(“Mercedes”); Node<CarType> walk = head; while ( ! walk.getData().equals(item ) ) walk=walk.getLink();

Finding the Mercedes (cont.) head walk item maker: Mercedes price: year: … Mercedes Loop repeats, walk moves through list CarType item=new CarType(…….); item.setMaker(“Mercedes”); Node<CarType> walk = head; while ( ! walk.getData().equals(item ) ) walk=walk.getLink();

Finding the Mercedes (cont.) head walk item maker: Mercedes price: year: … Mercedes CarType item=new CarType(…….); item.setMaker(“Mercedes”); Node<CarType> walk = head; while ( ! walk.getData().equals(item ) ) walk=walk.getLink();

Finding the Mercedes (cont.) head walk item maker: Mercedes price: year: … Mercedes CarType item=new CarType(…….); item.setMaker(“Mercedes”); Node<CarType> walk = head; while ( ! walk.getData().equals(item ) ) walk=walk.getLink(); FOUND!

Finding the Mercedes (cont.) head walk item maker: Mercedes price: year: … Mercedes Loop stops walk points to the node containing Mercedes Can return walk.getData() to the client, so that the client can access data members, such as price

What if no Mercedes? The code we looked at assumes there is a Mercedes in the linked list The following slides show the error that will occur if Mercedes is not in the linked list…

No Mercedes item head walk maker: Mercedes price: year: … CarType item=new CarType(…….); item.setMaker(“Mercedes”); Node<CarType> walk = head; while ( ! walk.getData().equals(item ) ) walk=walk.getLink();

No Mercedes (cont.) item head walk maker: Mercedes price: year: … CarType item=new CarType(…….); item.setMaker(“Mercedes”); Node<CarType> walk = head; while ( ! walk.getData().equals(item ) ) walk=walk.getLink();

No Mercedes (cont.) item head walk maker: Mercedes price: year: … CarType item=new CarType(…….); item.setMaker(“Mercedes”); Node<CarType> walk = head; while ( ! walk.getData().equals(item ) ) walk=walk.getLink();

No Mercedes (cont.) item head walk maker: Mercedes price: year: … CarType item=new CarType(…….); item.setMaker(“Mercedes”); Node<CarType> walk = head; while ( ! walk.getData().equals(item ) ) walk=walk.getLink();

No Mercedes (cont.) item head walk maker: Mercedes price: year: … CarType item=new CarType(…….); item.setMaker(“Mercedes”); Node<CarType> walk = head; while ( ! walk.getData().equals(item ) ) walk=walk.getLink();

No Mercedes (cont.) item head walk is set to null maker: Mercedes price: year: … CarType item=new CarType(…….); item.setMaker(“Mercedes”); Node<CarType> walk = head; while ( ! walk.getData().equals(item ) ) walk=walk.getLink();

No Mercedes (cont.) item head walk is set to null maker: Mercedes price: year: … CarType item=new CarType(…….); item.setMaker(“Mercedes”); Node<CarType> walk = head; while ( ! walk.getData().equals(item ) ) walk=walk.getLink();

No Mercedes (cont.) item head walk is set to null maker: Mercedes price: year: … CarType item=new CarType(…….); item.setMaker(“Mercedes”); Node<CarType> walk = head; while ( ! walk.getData().equals(item ) ) walk=walk.getLink(); Runtime error! Since walk is null .equals method can not be invoked.

Finding a Possible Mercedes head item maker: Mercedes price: year: … Let’s solve the problem, but let’s assume that item is passed in as a parameter (of type DataType). This is normally what would happen.

Finding a Possible Mercedes (cont.) head item maker: Mercedes price: year: … Node<CarType> walk = head; bool found = false; while (walk != null && !found ) { if ( walk.getData().equals( item ) ) found = true; if ( !found ) walk = walk.getNext(); }

Finding a Possible Mercedes (cont.) head walk item maker: Mercedes price: year: … Node<DataType> walk = head; bool found = false; while (walk != null && !found ) { if ( walk.getData().equals( item ) ) // overloaded == found = true; if ( !found ) walk = walk.getNext(); }

Finding a Possible Mercedes (cont.) head walk item maker: Mercedes price: year: … Node<DataType> walk = head; bool found = false; while (walk != null && !found ) { if ( walk.getData().equals( item ) ) // overloaded == found = true; if ( !found ) walk = walk.getNext(); }

Finding a Possible Mercedes (cont.) head walk item maker: Mercedes price: year: … Node<DataType> walk = head; bool found = false; while (walk != null && !found ) { if ( walk.getData().equals( item ) ) found = true; if ( !found ) walk = walk.getNext(); } found: false

Finding a Possible Mercedes (cont.) head walk item maker: Mercedes price: year: … Node<DataType> walk = head; bool found = false; while (walk != null && !found ) { if ( walk.getData().equals( item ) ) found = true; if ( !found ) walk = walk.getNext(); } found: false

Finding a Possible Mercedes (cont.) head walk item maker: Mercedes price: year: … Node<DataType> walk = head; bool found = false; while (walk != null && !found ) { if ( walk.getData().equals( item ) ) found = true; if ( !found ) walk = walk.getNext(); } found: false

Finding a Possible Mercedes (cont.) head walk item maker: Mercedes price: year: … Node<DataType> walk = head; bool found = false; while (walk != null && !found ) { if ( walk.getData().equals( item ) ) found = true; if ( !found ) walk = walk.getNext(); } found: false

Finding a Possible Mercedes (cont.) head walk item maker: Mercedes price: year: … Node<DataType> walk = head; bool found = false; while (walk != null && !found ) { if ( walk.getData().equals( item ) ) found = true; if ( !found ) walk = walk.getNext(); } found: false

Finding a Possible Mercedes (cont.) head walk item maker: Mercedes price: year: … Node<DataType> walk = head; bool found = false; while (walk != null && !found ) { if ( walk.getData().equals( item ) ) found = true; if ( !found ) walk = walk.getNext(); } found: false

Finding a Possible Mercedes (cont.) head walk item maker: Mercedes price: year: … Node<DataType> walk = head; bool found = false; while (walk != null && !found ) { if ( walk.getData().equals( item ) ) found = true; if ( !found ) walk = walk.getNext(); } found: false Notice that found is only set to true if Mercedes is found …

Finding a Possible Mercedes (cont.) head walk item maker: Mercedes price: year: … Node<DataType> walk = head; bool found = false; while (walk != null && !found ) { if ( walk.getData().equals( item ) ) found = true; if ( !found ) walk = walk.getNext(); } found: false then, !found is false and the loop exits

Finding a Possible Mercedes (cont.) head walk item maker: Mercedes price: year: … Node<DataType> walk = head; bool found = false; while (walk != null && !found ) { if ( walk.getData().equals( item ) ) found = true; if ( !found ) walk = walk.getNext(); } found: false If Mercedes is not found, ptr eventually gets set to null, as before.

Finding a Possible Mercedes (cont.) head walk item maker: Mercedes price: year: … Node<DataType> walk = head; bool found = false; while (walk != null && !found ) { if ( walk.getData().equals( item ) ) found = true; if ( !found ) walk = walk.getNext(); } found: false After going through the loop several times…

Finding a Possible Mercedes (cont.) head walk item maker: Mercedes price: year: … Node<DataType> walk = head; bool found = false; while (walk != null && !found ) { if ( walk.getData().equals( item ) ) found = true; if ( !found ) walk = walk.getNext(); } found: false

Finding a Possible Mercedes (cont.) head walk is set to null item maker: Mercedes price: year: … Node<DataType> walk = head; bool found = false; while (walk != null && !found ) { if ( walk.getData().equals( item ) ) found = true; if ( !found ) walk = walk.getNext(); } found: false

Finding a Possible Mercedes (cont.) head walk is set to null item maker: Mercedes price: year: … Node<DataType> walk = head; bool found = false; while (walk != null && !found ) { if ( walk.getData().equals( item ) ) found = true; if ( !found ) walk = walk.getNext(); } found: false

Finding a Possible Mercedes (cont.) head walk is set to null item maker: Mercedes price: year: … Node<DataType> walk = head; bool found = false; while (walk != null && !found ) { if ( walk.getData().equals( item ) ) found = true; if ( !found ) walk = walk.getNext(); } found: false Exit from loop with no runtime error

Another Case What if the linked list is empty to begin with? Try to consider all possible cases When a linked list is empty, the head reference(pointer) should always be set to null The head reference(pointer) would be set to null inside the constructor, when an empty linked list is first made

Empty List Case item head is set to null maker: Mercedes price: year: Node<DataType> walk = head; bool found = false; while (walk != null && !found ) { if ( walk.getData().equals( item ) ) found = true; if ( !found ) walk = walk.getNext(); }

Empty List Case (cont.) item head is set to null maker: Mercedes price: year: Node<DataType> walk = head; bool found = false; while (walk != null && !found ) { if ( walk.getData().equals( item ) ) found = true; if ( !found ) walk = walk.getNext(); } SAME CODE

Empty List Case (cont.) item head is set to null maker: Mercedes price: year: Node<DataType> walk = head; bool found = false; while (walk != null && !found ) { if ( walk.getData().equals( item ) ) found = true; if ( !found ) walk = walk.getNext(); }

Empty List Case (cont.) item head is set to null maker: Mercedes price: year: walk is set to null Node<DataType> walk = head; bool found = false; while (walk != null && !found ) { if ( walk.getData().equals( item ) ) found = true; if ( !found ) walk = walk.getNext(); }

Empty List Case (cont.) item head is set to null maker: Mercedes price: year: walk is set to null Node<DataType> walk = head; bool found = false; while (walk != null && !found ) { if ( walk.getData().equals( item ) ) found = true; if ( !found ) walk = walk.getNext(); }

Empty List Case (cont.) item head is set to null maker: Mercedes price: year: walk is set to null Node<DataType> walk = head; bool found = false; while (walk != null && !found ) { if ( walk.getData().equals( item ) ) found = true; if ( !found ) walk = walk.getNext(); } found: false

Empty List Case (cont.) item head is set to null maker: Mercedes price: year: operator == walk is set to null Node<DataType> walk = head; bool found = false; while (walk != null && !found ) { if ( walk.getData().equals( item ) ) found = true; if ( !found ) walk = walk.getNext(); } found: false

Empty List Case (cont.) item head is set to null maker: Mercedes price: year: operator == walk is set to null Node<DataType> walk = head; bool found = false; while (walk != null && !found ) { if ( walk.getData().equals( item ) ) found = true; if ( !found ) walk = walk.getNext(); } found: false Exit loop without runtime error

Inserting a New Node Let’s assume that we want to insert a new node at the beginning of a linked list Assume that the client passes in a parameter called element (of type DataType) We would like to place the element into a node and insert the node at the beginning of the linked list

Inserting a Node element head

Inserting a Node (cont.) element head All new nodes must be made in the heap, SO…

Inserting a Node (cont.) element head Node<DataType> ptr = new Node<DataType>();

Inserting a Node (cont.) element head ptr Node<DataType> ptr = new Node<DataType>();

Inserting a Node (cont.) element head ptr Node<DataType> ptr = new Node<DataType>(); Now we have to store element into the node

Inserting a Node (cont.) element head ptr Node<DataType> ptr = new Node<DataType>(); ptr.setData(element);

Inserting a Node (cont.) element head ptr Node<DataType> ptr = new Node<DataType>(); ptr.setData(element);

Inserting a Node (cont.) element head ptr Node<DataType> ptr = new Node<DataType>(); ptr.setData(element);

Inserting a Node (cont.) element head Now we have to think about how to make the reference(pointer) called “next” point to the first node in the list, to link it in ptr Node<DataType> ptr = new Node<DataType>(); ptr.setData(element);

Inserting a Node (cont.) element head You can’t successfully write code like this without thinking about addresses. ptr Node<DataType> ptr = new Node<DataType>(); ptr.setData(element);

Inserting a Node (cont.) element head REMEMBER…when you want to change the way a reference(pointer) points, you HAVE to assign a different address to it ptr Node<DataType> ptr = new Node<DataType>(); ptr.setData(element);

Inserting a Node (cont.) element head Right now, the reference(pointer) called “next” doesn’t have a valid address assigned to it. ptr Node<DataType> ptr = new Node<DataType>(); ptr.setData(element);

Inserting a Node (cont.) element head To store the correct address in it, we have to find the address of the first node of the linked list. ptr Node<DataType> ptr = new Node<DataType>(); ptr.setData(element);

Inserting a Node (cont.) element head Where is the address of the first node stored? ptr Node<DataType> ptr = new Node<DataType>(); ptr.setData(element);

Inserting a Node (cont.) element head Now think, the address would be stored in something that points to it. So where is it stored? ptr Node<DataType> ptr = new Node<DataType>(); ptr.setData(element);

Inserting a Node (cont.) element head ptr That’s right, in the head reference(pointer). Node<DataType> ptr = new Node<DataType>(); ptr.setData(element);

Inserting a Node (cont.) element head So now, all we have to do is copy that address into the reference(pointer) called “next” ptr Node<DataType> ptr = new Node<DataType>(); ptr.setData(element);

Inserting a Node (cont.) element head ptr Node<DataType> ptr = new Node<DataType>(); ptr.setData(element);

Inserting a Node (cont.) element head ptr Node<DataType> ptr = new Node<DataType>(); ptr.setData(element); ptr.setNext( head);

Inserting a Node (cont.) element head ptr Node<DataType> ptr = new Node<DataType>(); ptr.setData(element); ptr.setNext( head);

Inserting a Node (cont.) element head Well, it’s been inserted. But head should point to the first node now. ptr Node<DataType> ptr = new Node<DataType>(); ptr.setData(element); ptr.setNext( head);

Inserting a Node (cont.) element head REMEMBER…when you want to change the way a reference(pointer) points, you have to assign a different address to it ptr Node<DataType> ptr = new Node<DataType>(); ptr.setData(element); ptr.setNext( head);

Inserting a Node (cont.) element head We’d like head to point to the new node, so what stores the address of the new node? ptr Node<DataType> ptr = new Node<DataType>(); ptr.setData(element); ptr.setNext( head);

Inserting a Node (cont.) element head That’s right, ptr. So now all we have to do is assign the address stored in ptr to the head reference(pointer). ptr Node<DataType> ptr = new Node<DataType>(); ptr.setData(element); ptr.setNext( head);

Inserting a Node (cont.) element head ptr Node<DataType> ptr = new Node<DataType>(); ptr.setData(element); ptr.setNext( head);

Inserting a Node (cont.) element head ptr Node<DataType> ptr = new Node<DataType>(); ptr.setData(element); ptr.setNext( head); head=ptr;

Inserting a Node (cont.) element head ptr Node<DataType> ptr = new Node<DataType>(); ptr.setData(element); ptr.setNext( head); head=ptr;

Inserting a Node (cont.) element head ptr Node<DataType> ptr = new Node<DataType>(); ptr.setData(element); ptr.setNext( head); head=ptr;

REMEMBER… Always use drawings when working with linked lists, until you become an expert When you want to change the way a reference(pointer) points, you have to assign a different address to it You can find the address you need by looking at other reference(pointer)s (remember that they store addresses)

Inserting into the Middle (between nodes) of a Linked List Suppose we know that there is a Mercedes in a linked list We would like to insert a node containing Honda right after it We first find the Mercedes, using code that we looked at before

Inserting a Node head element maker: Mercedes price: year: … Node<DataType> ptr = head; while ( ptr.getData.equals(element) ) // element is a parameter ptr = ptr.getNext();

Inserting a Node (cont.) head element maker: Mercedes price: year: … Mercedes After this code executes, ptr points to the node that has Mercedes. Node<DataType> ptr = head; while ( ptr.getData.equals(element) ) // element is a parameter ptr = ptr.getNext();

Inserting a Node (cont.) head element ptr maker: Mercedes price: year: … Mercedes After this code executes, ptr points to the node that has Mercedes. Node<DataType> ptr = head; while ( ptr.getData.equals(element) ) // element is a parameter ptr = ptr.getNext();

Inserting a Node (cont.) head element ptr maker: Mercedes price: year: … Mercedes Now we would like to insert a CarType object called elementToInsert (containing Honda), which would also be passed in as a parameter, right after the Mercedes

Inserting a Node (cont.) head ptr maker: Honda price: 5000 year: 1985 … Mercedes elementToInsert

Inserting a Node (cont.) head ptr maker: Honda price: 5000 year: 1985 operator != … Mercedes elementToInsert Well, all new nodes are created in the heap, SO…..

Inserting a Node (cont.) head ptr maker: Honda price: 5000 year: 1985 operator != … Mercedes elementToInsert (object of Car Type) First create a new Node for new Data Node<DataType> newNode = new Node<DataType>(elementToInsert);

Inserting a Node (cont.) head ptr maker: Honda price: 5000 year: 1985 … Mercedes elementToInsert newNode Node<DataType> newNode = new Node<DataType>(elementToInsert);

Inserting a Node (cont.) head ptr maker: Honda price: 5000 year: 1985 … Mercedes elementToInsert newNode Node<DataType> newNode = new Node<DataType>(elementToInsert);

Inserting a Node (cont.) head ptr maker: Honda price: 5000 year: 1985 … Mercedes elementToInsert newNode Node<DataType> newNode = new Node<DataType>(elementToInsert);

Inserting a Node (cont.) head ptr … Mercedes newNode Node<DataType> *newNode = new Node<DataType>; newNode->info = elementToInsert;

Inserting a Node (cont.) head ptr Now, what we want is shown by the dashed arrows; this would cause the insertion of the node … Mercedes newNode Node<DataType> newNode = new Node<DataType>(elementToInsert);

Inserting a Node (cont.) head ptr We have two reference(pointer)s we need to change – but we have to be careful about the way we change them … Mercedes newNode Node<DataType> newNode = new Node<DataType>(elementToInsert);

Inserting a Node (cont.) head ptr If we change the left reference(pointer) first, we will no longer be able to access the last node (memory leak) … Mercedes newNode Node<DataType> newNode = new Node<DataType>(elementToInsert);

Inserting a Node (cont.) head ptr So, we first have to assign the address of the last node into the “next” reference(pointer) of the new node … Mercedes newNode Node<DataType> newNode = new Node<DataType>(elementToInsert);

Inserting a Node (cont.) head ptr Where is the address of the last node stored? … Mercedes newNode Node<DataType> newNode = new Node<DataType>(elementToInsert);

Inserting a Node (cont.) head ptr That’s right, it is stored in ptr.next … Mercedes newNode Node<DataType> newNode = new Node<DataType>(elementToInsert);

Inserting a Node (cont.) head ptr … Mercedes newNode Node<DataType> newNode = new Node<DataType>(elementToInsert); newNode.setNext( ptr.getNext());

Inserting a Node (cont.) head ptr … Mercedes newNode Node<DataType> newNode = new Node<DataType>(elementToInsert); newNode.setNext( ptr.getNext());

Inserting a Node (cont.) head ptr … Mercedes newNode Node<DataType> newNode = new Node<DataType>(elementToInsert); newNode.setNext( ptr.getNext()); ptr.setNext (newNode);

Inserting a Node (cont.) head ptr … Mercedes Mercedes newNode Node<DataType> newNode = new Node<DataType>(elementToInsert); newNode.setNext( ptr.getNext()); ptr.setNext (newNode);

Removing a Node Suppose we definitely know there is a Mercedes in the linked list and we wish to remove the node that contains it We need to find the node first

Removing a Node (cont.) head … Mercedes

Removing a Node (cont.) ptr head … Mercedes

Removing a Node (cont.) ptr head … Mercedes When it is found, we need to join the node in front of it to the node after it.

Removing a Node (cont.) ptr head … Mercedes When it is found, we need to join the node in front of it to the node after it.

Removing a Node (cont.) ptr head … Mercedes But how can we access the “next” reference(pointer) of the node in front, so we can change the address it stores? (we can’t)

Removing a Node (cont.) ptr head … Mercedes The way to solve the problem is by having ptr stop on the node BEFORE the node that has Mercedes

Removing a Node (cont.) ptr head … Mercedes

Removing a Node (cont.) ptr head … Mercedes

Removing a Node (cont.) ptr head … Mercedes If ptr stops here, then we CAN change the address stored in the “next” reference(pointer). So we have to set up a loop appropriately.

Removing a Node (cont.) head … Mercedes

Removing a Node (cont.) head … element contains Mercedes Node<DataType> walk = head; Node <DataType>prev=null; while (walk!= null ) && (walk.getData().equals(element) { prev=walk; walk=walk.getNext(); }

Removing a Node (cont.) head … Mercedes passed in from the client as a parameter Node<DataType> walk = head; Node <DataType>prev=null; while (walk!= null ) && (walk.getData().equals(element) { prev=walk; walk=walk.getNext(); }

Removing a Node (cont.) head … Mercedes BUT…what if Mercedes is in the first node?

Removing a Node (cont.) head … Mercedes BUT…what if Mercedes is in the first node? We need to handle the first node differently.

Removing a Node (cont.) head … Mercedes

Removing a Node (cont.) head … Node<DataType> ptr = head; Mercedes Node<DataType> ptr = head; if ( head.getData().equals( element ) ) head = head.getNext();

Removing a Node (cont.) head … Node<DataType> ptr = head; Mercedes Node<DataType> ptr = head; if ( head!=null && head.getData().equals( element ) ) head = head.getNext();

Removing a Node (cont.) ptr head … Node<DataType> ptr = head; Mercedes Node<DataType> ptr = head; if ( head!=null && head.getData().equals( element ) ) head = head.getNext();

Removing a Node (cont.) ptr head … Node<DataType> ptr = head; Mercedes Node<DataType> ptr = head; if ( head!=null && head.getData().equals( element ) ) head = head.getNext();

Removing a Node (cont.) ptr head … Node<DataType> ptr = head; Mercedes Node<DataType> ptr = head; if ( head!=null && head.getData().equals( element ) ) head = head.getNext();

Removing a Node (cont.) ptr head … Node<DataType> ptr = head; Mercedes Node<DataType> ptr = head; if ( head!=null && head.getData().equals( element ) ) head = head.getNext();

Removing a Node (cont.) ptr head … Node<DataType> ptr = head; Well, head points to the beginning of the new linked list, node pointed by ptr will be göne to garbage ptr head … Mercedes Node<DataType> ptr = head; if ( head!=null && head.getData().equals( element ) ) head = head.getNext();

Removing a Node (cont.) ptr head …

Removing a Node (cont.) ptr head … Now, let’s consider the other case. Node<DataType> ptr = head; if ( head!=null && head.getData().equals( element ) ) head = head.getNext();

Removing a Node (cont.) head … Mercedes Node<DataType> ptr = head; if ( head!=null && head.getData().equals( element ) ) head = head.getNext(); else { while ( walk!=null && !walk.getData().equals(element ) ){ prev=walk; walk = walk.getNext(); }

Removing a Node (cont.) head … Mercedes This is the loop that we thought of before. else { while ( walk!=null && !walk.getData().equals(element ) ){ prev=walk; walk = walk.getNext(); }

Removing a Node (cont.) head … Mercedes It will find the node BEFORE the node that has Mercedes. else { while ( walk!=null && !walk.getData().equals(element ) ){ prev=walk; walk = walk.getNext(); }

Removing a Node (cont.) walk prev head … Mercedes It will find the node BEFORE the node that has Mercedes. prev walk head … Mercedes else { while ( walk!=null && !walk.getData().equals(element ) ){ prev=walk; walk = walk.getNext(); }

Removing a Node (cont.) walk prev head … Mercedes Now we need to join the node before Mercedes to the node after Mercedes else { while ( walk!=null && !walk.getData().equals(element ) ){ prev=walk; walk = walk.getNext(); }

Removing a Node (cont.) walk prev head … Mercedes else { while ( walk!=null && !walk.getData().equals(element ) ){ prev=walk; walk = walk.getNext(); } if(walk!=null) //if target is found prev.setNext(walk.getNext();

Removing a Node (cont.) walk prev head … Mercedes else { while ( walk!=null && !walk.getData().equals(element ) ){ prev=walk; walk = walk.getNext(); } if(walk!=null) //if target is found prev.setNext(walk.getNext();

Removing a Node (cont.) walk prev head … Mercedes else { while ( walk!=null && !walk.getData().equals(element ) ){ prev=walk; walk = walk.getNext(); } if(walk!=null) //if target is found prev.setNext(walk.getNext();

Removing a Node (cont.) walk prev head … Mercedes else { while ( walk!=null && !walk.getData().equals(element ) ){ prev=walk; walk = walk.getNext(); } if(walk!=null) //if target is found prev.setNext(walk.getNext();

Removing a Node (cont.) walk prev head … Mercedes else { while ( walk!=null && !walk.getData().equals(element ) ){ prev=walk; walk = walk.getNext(); } if(walk!=null) //if target is found prev.setNext(walk.getNext(); But how will we free the node that has Mercedes? No: Garbage Collector will handle it

Removing a Node (cont.) walk prev head … else { while ( walk!=null && !walk.getData().equals(element ) ){ prev=walk; walk = walk.getNext(); } if(walk!=null) //if target is found prev.setNext(walk.getNext();

What If? What if Mercedes is the last node in the linked list Would our code still work? Try to consider every possible situation in code design

Removing the Last Node walk prev head … Mercedes After looping, ptr stops on the next-to-the-last node else { while ( walk!=null && !walk.getData().equals(element ) ){ prev=walk; walk = walk.getNext(); } if(walk!=null) //if target is found prev.setNext(walk.getNext();

Removing the Last Node (cont.) prev walk head … Mercedes else { while ( walk!=null && !walk.getData().equals(element ) ){ prev=walk; walk = walk.getNext(); } if(walk!=null) //if target is found prev.setNext(walk.getNext(); //will disconnect last node from linked list

Removing the Last Node (cont.) walk prev head … Mercedes Java garbage collector will remove last node else { while ( walk!=null && !walk.getData().equals(element ) ){ prev=walk; walk = walk.getNext(); } if(walk!=null) //if target is found prev.setNext(walk.getNext(); //will disconnect last node from linked list

Removing the Last Node (cont.) prev head … The code works in removing the last node.

Working With Linked Lists As you can see, sometimes you have to do a lot of thinking and problem-solving when working with linked lists It is not always obvious how to write code You can’t memorize the code, because it will not quite fit situations that you will encounter It is a matter of using logic (and knowing a few tricks of the trade)

Code for Removing a Node Here is the resulting code for removing a node. It is assumes the node we are looking for is in the linked list.

Code for Removing a Node (cont.) This code can be simplified by using a dummy head node A header node is like any other node, except it doesn’t contain data. Since we know the first node doesn’t contain data, it can’t contain Mercedes.

Removing a Node But this code assumes that there definitely is a Mercedes in the linked list Let’s refine it a little Suppose we are not really sure if there is a Mercedes in the linked list to delete Or suppose the linked list is empty to begin with Always try to handle every case

Refining Code with Header Node

Refining Code with Header Node (cont.) Node<DataType> *ptr = head; bool found = false; while ( ptr->next->info != element ) ptr = ptr->next; Node<DataType> *ptr2 = ptr->next; ptr->next = ptr2->next; delete ptr2; We’ll use our found variable, like before.

Refining Code with Header Node (cont.) Node<DataType> *ptr = head; bool found = false; while ( ptr->next->info != element ) ptr = ptr->next; Node<DataType> *ptr2 = ptr->next; ptr->next = ptr2->next; delete ptr2; This will give us a runtime error if we have an empty list. Let’s test for it in a loop heading.

Refining Code with Header Node (cont.) Node<DataType> *ptr = head; bool found = false; while ( ptr->next->info != element ) ptr = ptr->next; Node<DataType> *ptr2 = ptr->next; ptr->next = ptr2->next; delete ptr2; We’ll make a new loop and shove this part inside.

Refining Code with Header Node (cont.) Node<DataType> *ptr = head; bool found = false; while ( ptr->next != null ) { while ( ptr->next->info != element ) ptr = ptr->next; Node<DataType> *ptr2 = ptr->next; ptr->next = ptr2->next; delete ptr2; }

Refining Code with Header Node (cont.) Node<DataType> *ptr = head; bool found = false; while ( ptr->next != null ) { while ( ptr->next->info != element ) ptr = ptr->next; Node<DataType> *ptr2 = ptr->next; ptr->next = ptr2->next; delete ptr2; } Now we want the removal code if ptr->next->info IS equal to element

Refining Code with Header Node (cont.) Node<DataType> *ptr = head; bool found = false; while ( ptr->next != null ) { if ( ptr->next->info == element ) ptr = ptr->next; Node<DataType> *ptr2 = ptr->next; ptr->next = ptr2->next; delete ptr2; } Now we want the removal code if ptr->next->info IS equal to element

Refining Code with Header Node (cont.) Node<DataType> *ptr = head; bool found = false; while ( ptr->next != null ) { if ( ptr->next->info == element ) { Node<DataType> *ptr2 = ptr->next; ptr->next = ptr2->next; delete ptr2; }

Refining Code with Header Node (cont.) Node<DataType> *ptr = head; bool found = false; while ( ptr->next != null ) { if ( ptr->next->info == element ) { Node<DataType> *ptr2 = ptr->next; ptr->next = ptr2->next; delete ptr2; } If we remove a node, we need to break out of the loop.

Refining Code with Header Node (cont.) Node<DataType> *ptr = head; bool found = false; while ( ptr->next != null && !found ) { if ( ptr->next->info == element ) { Node<DataType> *ptr2 = ptr->next; ptr->next = ptr2->next; delete ptr2; found = true; } If we remove a node, we need to break out of the loop.

Refining Code with Header Node (cont.) Node<DataType> *ptr = head; bool found = false; while ( ptr->next != null && !found ) { if ( ptr->next->info == element ) { Node<DataType> *ptr2 = ptr->next; ptr->next = ptr2->next; delete ptr2; found = true; } Now, we just need to advance ptr if we didn’t remove a node.

Refining Code with Header Node (cont.) Node<DataType> *ptr = head; bool found = false; while ( ptr->next != null && !found ) { if ( ptr->next->info == element ) { Node<DataType> *ptr2 = ptr->next; ptr->next = ptr2->next; delete ptr2; found = true; } if ( !found ) ptr = ptr->next; Final result.

Linked List vs. Arrays When computer scientists decide on whether or not to use an array or linked list for data, the decision is usually based on two factors: Speed Conservation of Memory (RAM)

Speed In some situations, an array can be faster than a linked list, such as when a calculated index is used to access an element In other situations, a linked list can be faster than an array, such as when removing an element from the middle (as we saw before) we usually need to search for the element to remove, but we search for it in both the array and linked list