Download presentation
Presentation is loading. Please wait.
1
CENG 218 Classes and Data Structures
2
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
3
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
4
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…
5
changeSize Function 33 … 25 75 10 12 56 32 73 87 New element needs to be put into array, so changeSize function is called
6
changeSize Function (cont.)
… 25 75 10 12 56 32 73 87 … new array is made
7
changeSize Function (cont.)
… 25 75 10 12 56 32 73 87 … 25 75 10 12 56 32 73 87 elements are copied over one by one using a for loop
8
changeSize Function (cont.)
33 … 25 75 10 12 56 32 73 87 33 Then, the new element can be put in
9
changeSize Function (cont.)
… 25 75 10 12 56 32 73 87 33 This process would take place every time a new element needs to be inserted.
10
changeSize Function (cont.)
… 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.
11
changeSize Function (cont.)
… 25 75 10 12 56 32 73 87 33 Suppose the element at the end of the array needs to be removed.
12
changeSize Function (cont.)
… 25 75 10 12 56 32 73 87 33 … The changeSize function is called and a new, smaller array is made.
13
changeSize Function (cont.)
… 25 75 10 12 56 32 73 87 33 … 25 75 10 12 56 32 73 87 The elements are copied over one by one, using a for loop.
14
changeSize Function (cont.)
… 25 75 10 12 56 32 73 87 This method of array expansion/contraction is largely inefficient, because there is too much element copying.
15
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)
16
A Better Method (cont.) 25 75
17
A Better Method (cont.) 25 75 10
18
A Better Method (cont.) 25 75 10 12
19
A Better Method (cont.) 33 25 75 10 12 Array is full, so call changeSize function to double the size.
20
A Better Method (cont.) 25 75 10 12 33
21
A Better Method (cont.) 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%
22
A Better Method (cont.) 25 75 10 12 33 49 29
23
A Better Method (cont.) 25 75 10 12 33 49
24
A Better Method (cont.) 25 75 10 12 33
25
A Better Method (cont.) 25 75 10 12
26
A Better Method (cont.) 25 75 10
27
A Better Method (cont.) 25 75 Array is 25% utilized, so use changeSize function to cut the size of the array in half.
28
A Better Method (cont.) 25 75 Array is 25% utilized, so use changeSize function to cut the size of the array in half.
29
A Better Method (cont.) 25 75 Using this method, memory is still conserved. There is element copying every time changeSize is called, but it isn’t bad.
30
A Better Method (cont.) 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.
31
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.
32
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; }
33
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
34
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.
35
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.
36
Example of a Linked Structure
head each node is divided into two sections, for the two members of the Node.
37
Example of a Linked Structure (cont.)
head The left section is the data member.
38
Example of a Linked Structure (cont.)
head The right section is the reference(pointer)(or reference) called “next”.
39
Example of a Linked Structure (cont.)
head The head reference(pointer) would be saved in the private section of a data structure class.
40
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).
41
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.
42
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.
43
Linked List Advantages (cont.)
… … 5 3 2 1 7 Removing an element from the middle of a linked list is fast.
44
Linked List Advantages (cont.)
Assume we have an array having 100,000 elements … … 25 75 10 12 33 49 29 87 Removing elements from the middle of an array (without leaving gaps) is more problematic.
45
Linked List Advantages (cont.)
Assume we have an array having 100,000 elements … … 25 75 10 33 49 29 87 Removing elements from the middle of an array (without leaving gaps) is more problematic.
46
Linked List Advantages (cont.)
Assume we have an array having 100,000 elements … … 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…
47
Linked List Advantages (cont.)
Assume we have an array having 100,000 elements … … 25 75 10 33 49 29 87
48
Linked List Advantages (cont.)
Assume we have an array having 100,000 elements … … 25 75 10 33 49 29 87
49
Linked List Advantages (cont.)
Assume we have an array having 100,000 elements … … 25 75 10 33 49 29 87
50
Linked List Advantages (cont.)
Assume we have an array having 100,000 elements … … 25 75 10 33 49 29 87
51
Linked List Advantages (cont.)
Assume we have an array having 100,000 elements … … 25 75 10 33 49 29 87 Only 100,000 more to go!
52
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.
53
Linked List Advantages (cont.)
head Linked List Array
54
Accessing info head To access the info in the first node:
head.getData()
55
Accessing info (cont.) head To access the info in the second node:
head.getLink().getData()
56
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.
57
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;
58
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();
59
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();
60
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();
61
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();
62
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();
63
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();
64
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();
65
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();
66
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();
67
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();
68
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();
69
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!
70
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
71
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…
72
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();
73
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();
74
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();
75
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();
76
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();
77
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();
78
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();
79
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.
80
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.
81
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(); }
82
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(); }
83
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(); }
84
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
85
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
86
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
87
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
88
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
89
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
90
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 …
91
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
92
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.
93
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…
94
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
95
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
96
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
97
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
98
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
99
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(); }
100
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
101
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(); }
102
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(); }
103
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(); }
104
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
105
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
106
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
107
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
108
Inserting a Node element head
109
Inserting a Node (cont.)
element head All new nodes must be made in the heap, SO…
110
Inserting a Node (cont.)
element head Node<DataType> ptr = new Node<DataType>();
111
Inserting a Node (cont.)
element head ptr Node<DataType> ptr = new Node<DataType>();
112
Inserting a Node (cont.)
element head ptr Node<DataType> ptr = new Node<DataType>(); Now we have to store element into the node
113
Inserting a Node (cont.)
element head ptr Node<DataType> ptr = new Node<DataType>(); ptr.setData(element);
114
Inserting a Node (cont.)
element head ptr Node<DataType> ptr = new Node<DataType>(); ptr.setData(element);
115
Inserting a Node (cont.)
element head ptr Node<DataType> ptr = new Node<DataType>(); ptr.setData(element);
116
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);
117
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);
118
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);
119
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);
120
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);
121
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);
122
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);
123
Inserting a Node (cont.)
element head ptr That’s right, in the head reference(pointer). Node<DataType> ptr = new Node<DataType>(); ptr.setData(element);
124
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);
125
Inserting a Node (cont.)
element head ptr Node<DataType> ptr = new Node<DataType>(); ptr.setData(element);
126
Inserting a Node (cont.)
element head ptr Node<DataType> ptr = new Node<DataType>(); ptr.setData(element); ptr.setNext( head);
127
Inserting a Node (cont.)
element head ptr Node<DataType> ptr = new Node<DataType>(); ptr.setData(element); ptr.setNext( head);
128
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);
129
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);
130
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);
131
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);
132
Inserting a Node (cont.)
element head ptr Node<DataType> ptr = new Node<DataType>(); ptr.setData(element); ptr.setNext( head);
133
Inserting a Node (cont.)
element head ptr Node<DataType> ptr = new Node<DataType>(); ptr.setData(element); ptr.setNext( head); head=ptr;
134
Inserting a Node (cont.)
element head ptr Node<DataType> ptr = new Node<DataType>(); ptr.setData(element); ptr.setNext( head); head=ptr;
135
Inserting a Node (cont.)
element head ptr Node<DataType> ptr = new Node<DataType>(); ptr.setData(element); ptr.setNext( head); head=ptr;
136
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)
137
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
138
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();
139
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();
140
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();
141
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
142
Inserting a Node (cont.)
head ptr maker: Honda price: 5000 year: 1985 … Mercedes elementToInsert
143
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…..
144
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);
145
Inserting a Node (cont.)
head ptr maker: Honda price: 5000 year: 1985 … Mercedes elementToInsert newNode Node<DataType> newNode = new Node<DataType>(elementToInsert);
146
Inserting a Node (cont.)
head ptr maker: Honda price: 5000 year: 1985 … Mercedes elementToInsert newNode Node<DataType> newNode = new Node<DataType>(elementToInsert);
147
Inserting a Node (cont.)
head ptr maker: Honda price: 5000 year: 1985 … Mercedes elementToInsert newNode Node<DataType> newNode = new Node<DataType>(elementToInsert);
148
Inserting a Node (cont.)
head ptr … Mercedes newNode Node<DataType> *newNode = new Node<DataType>; newNode->info = elementToInsert;
149
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);
150
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);
151
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);
152
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);
153
Inserting a Node (cont.)
head ptr Where is the address of the last node stored? … Mercedes newNode Node<DataType> newNode = new Node<DataType>(elementToInsert);
154
Inserting a Node (cont.)
head ptr That’s right, it is stored in ptr.next … Mercedes newNode Node<DataType> newNode = new Node<DataType>(elementToInsert);
155
Inserting a Node (cont.)
head ptr … Mercedes newNode Node<DataType> newNode = new Node<DataType>(elementToInsert); newNode.setNext( ptr.getNext());
156
Inserting a Node (cont.)
head ptr … Mercedes newNode Node<DataType> newNode = new Node<DataType>(elementToInsert); newNode.setNext( ptr.getNext());
157
Inserting a Node (cont.)
head ptr … Mercedes newNode Node<DataType> newNode = new Node<DataType>(elementToInsert); newNode.setNext( ptr.getNext()); ptr.setNext (newNode);
158
Inserting a Node (cont.)
head ptr … Mercedes Mercedes newNode Node<DataType> newNode = new Node<DataType>(elementToInsert); newNode.setNext( ptr.getNext()); ptr.setNext (newNode);
159
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
160
Removing a Node (cont.) head … Mercedes
161
Removing a Node (cont.) ptr head … Mercedes
162
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.
163
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.
164
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)
165
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
166
Removing a Node (cont.) ptr head … Mercedes
167
Removing a Node (cont.) ptr head … Mercedes
168
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.
169
Removing a Node (cont.) head … Mercedes
170
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(); }
171
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(); }
172
Removing a Node (cont.) head …
Mercedes BUT…what if Mercedes is in the first node?
173
Removing a Node (cont.) head …
Mercedes BUT…what if Mercedes is in the first node? We need to handle the first node differently.
174
Removing a Node (cont.) head … Mercedes
175
Removing a Node (cont.) head … Node<DataType> ptr = head;
Mercedes Node<DataType> ptr = head; if ( head.getData().equals( element ) ) head = head.getNext();
176
Removing a Node (cont.) head … Node<DataType> ptr = head;
Mercedes Node<DataType> ptr = head; if ( head!=null && head.getData().equals( element ) ) head = head.getNext();
177
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();
178
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();
179
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();
180
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();
181
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();
182
Removing a Node (cont.) ptr head …
183
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();
184
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(); }
185
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(); }
186
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(); }
187
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(); }
188
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(); }
189
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();
190
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();
191
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();
192
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();
193
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
194
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();
195
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
196
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();
197
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
198
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
199
Removing the Last Node (cont.)
prev head … The code works in removing the last node.
200
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)
201
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.
202
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.
203
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
204
Refining Code with Header Node
205
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.
206
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.
207
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.
208
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; }
209
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
210
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
211
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; }
212
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.
213
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.
214
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.
215
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.
216
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)
217
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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.