83. Remove Duplicates from Sorted List
Easy
Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1:
Input: 1->1->2 Output: 1->2
Example 2:
Input: 1->1->2->3->3 Output: 1->2->3
package leetcode.easy;
public class RemoveDuplicatesFromSortedList {
@org.junit.Test
public void test() {
ListNode l11 = new ListNode(1);
ListNode l12 = new ListNode(1);
ListNode l13 = new ListNode(2);
l11.next = l12;
l12.next = l13;
l13.next = null;
print(l11);
ListNode l21 = new ListNode(1);
ListNode l22 = new ListNode(1);
ListNode l23 = new ListNode(2);
ListNode l24 = new ListNode(3);
ListNode l25 = new ListNode(3);
l21.next = l22;
l22.next = l23;
l23.next = l24;
l24.next = l25;
l25.next = null;
print(l21);
ListNode l1 = deleteDuplicates(l11);
print(l1);
ListNode l2 = deleteDuplicates(l21);
print(l2);
}
private static void print(ListNode l) {
while (l != null) {
System.out.print(l.val);
if (l.next != null) {
System.out.print("->");
}
l = l.next;
}
System.out.println();
}
public ListNode deleteDuplicates(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;
}
}