Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit bf457b3

Browse files
committed
Added 'remove' method to remove by element in CustomLinkedList
1 parent c154319 commit bf457b3

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

src/main/java/br/com/zevolution/datastructure/linkedlist/CustomLinkedList.java

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,33 @@ public void removeFirst() {
5858
}
5959
}
6060

61+
public void remove(Object element) {
62+
Node current = this.first;
63+
Node previous = null;
64+
65+
if (current.getElement() == element) {
66+
this.first = current.getNext();
67+
current = null;
68+
this.totalElements--;
69+
return;
70+
}
71+
72+
while (current != null) {
73+
if (current.getElement() == element) {
74+
break;
75+
}
76+
77+
previous = current;
78+
current = current.getNext();
79+
}
80+
81+
if (current == null) return;
82+
83+
previous.setNext(current.getNext());
84+
current = null;
85+
this.totalElements--;
86+
}
87+
6188
public Object get(int position) {
6289
return this.getNode(position).getElement();
6390
}

src/test/java/br/com/zevolution/datastructure/linkedlist/CustomLinkedListTest.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,4 +93,18 @@ public void should_ThrowException_When_NoSuchElement() {
9393
linkedList.removeFirst();
9494
}
9595

96+
@Test
97+
public void should_RemoveMiddleElement() {
98+
CustomLinkedList linkedList = new CustomLinkedList();
99+
linkedList.add("Bia");
100+
linkedList.add("Lucas");
101+
linkedList.add("Laura");
102+
103+
linkedList.remove("Lucas");
104+
105+
assertEquals(2, linkedList.size());
106+
assertEquals("Bia", linkedList.get(0));
107+
assertEquals("Laura", linkedList.get(1));
108+
}
109+
96110
}

0 commit comments

Comments
 (0)