-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemoveDuplicatesFromSortedList.Java
More file actions
26 lines (21 loc) · 1.06 KB
/
Copy pathRemoveDuplicatesFromSortedList.Java
File metadata and controls
26 lines (21 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.
public class RemoveDuplicatesFromSortedList {
public static void main(String[] args) {
}
public static ListNode solution(ListNode head) {
ListNode current = head;
while (current != null && current.next != null) {
if (current.next.val == current.val) {
current.next = current.next.next;
} else {
current = current.next;
}
}
return head;
}
}
// explanation:
// We first create a pointer: current, that points to the head of the linkedlist. Then we iterate throught he linkedlist.
// while the current node and next node is not null, we check if the value of the current node equals to the value of the next node.
// If they are equal, we point the next node to the next next node, effectively removing the duplicate node.
// If they are not equal, we move the current pointer to the next node to continue the iteration