Skip to content

Commit

Permalink
83. Remove Duplicates from Sorted List (#35)
Browse files Browse the repository at this point in the history
* 83. Remove Duplicates from Sorted List

* Fix formatting
  • Loading branch information
xtenzQ authored Jul 26, 2024
1 parent 18cdf85 commit 6e71704
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -81,4 +81,24 @@ public static ListNode middleNode(ListNode head) {

return slow;
}

/**
* Deletes all duplicates such that each element appears only once
*
* @param head head of linked list
* @return linked list with unique elements
* @implNote This method runs in {@code O(n)} time complexity and {@code O(1)} space complexity
* @see <a href="https://leetcode.com/problems/remove-duplicates-from-sorted-list/">83. Remove Duplicates from Sorted List</a>
*/
public static ListNode deleteDuplicates(ListNode head) {
ListNode pointer = head;
while (pointer != null && pointer.next != null) {
if (pointer.val == pointer.next.val) {
pointer.next = pointer.next.next;
} else {
pointer = pointer.next;
}
}
return head;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import org.junit.jupiter.api.Test;

import static com.xtenzq.linkedlist.FastPointers.deleteDuplicates;
import static com.xtenzq.linkedlist.FastPointers.getMiddle;
import static com.xtenzq.linkedlist.FastPointers.hasCycle;
import static com.xtenzq.linkedlist.FastPointers.middleNode;
Expand Down Expand Up @@ -60,4 +61,19 @@ void middleNode_case1() {
void middleNode_case2() {
assertEquals(buildLinkedList(4, 5, 6), middleNode(buildLinkedList(1,2,3,4,5,6)));
}

@Test
void deleteDuplicates_case1() {
assertEquals(buildLinkedList(1, 2, 3, 4, 5), deleteDuplicates(buildLinkedList(1, 2, 3, 3, 4, 4, 5)));
}

@Test
void deleteDuplicates_case2() {
assertEquals(buildLinkedList(1), deleteDuplicates(buildLinkedList(1)));
}

@Test
void deleteDuplicates_case3() {
assertEquals(buildLinkedList(1), deleteDuplicates(buildLinkedList(1, 1, 1)));
}
}

0 comments on commit 6e71704

Please sign in to comment.