Skip to content

Commit a48ff74

Browse files
committed
Merge pull request careermonk#1 from ayusmand/master
List length needs to be updated on remove operation.
2 parents 78dbc99 + c909d68 commit a48ff74

File tree

1 file changed

+8
-0
lines changed

1 file changed

+8
-0
lines changed

Diff for: src/chapter03linkedlists/LinkedList.java

+8
Original file line numberDiff line numberDiff line change
@@ -115,13 +115,17 @@ public synchronized ListNode removeFromEnd() {
115115
ListNode p = head, q = null, next = head.getNext();
116116
if (next == null) {
117117
head = null;
118+
// reduce the length of the list
119+
length-=1;
118120
return p;
119121
}
120122
while((next = p.getNext()) != null) {
121123
q = p;
122124
p = next;
123125
}
124126
q.setNext(null);
127+
// reduce the length of the list
128+
length-=1;
125129
return p;
126130
}
127131

@@ -132,12 +136,16 @@ public synchronized void removeMatched(ListNode node) {
132136
return;
133137
if (node.equals(head)) {
134138
head = head.getNext();
139+
// reduce the length of the list
140+
length-=1;
135141
return;
136142
}
137143
ListNode p = head, q = null;
138144
while((q = p.getNext()) != null) {
139145
if (node.equals(q)) {
140146
p.setNext(q.getNext());
147+
// reduce the length of the list
148+
length-=1;
141149
return;
142150
}
143151
p = q;

0 commit comments

Comments
 (0)