给定一个排序链表,删除所有重复元素,使链表中的元素只出现一次。
例一:
输入: 1->1->2
输出: 1->2
例二:
输入: 1->1->2->3->3
输出: 1->2->3
/*
* 83. Remove Duplicates from Sorted List
* https://leetcode.com/problems/remove-duplicates-from-sorted-list/
* https://www.whosneo.com/83-remove-duplicates-from-sorted-list/
*/
public class DeleteDuplicates {
public static void main(String[] args) {
ListNode head = new ListNode(1);
ListNode node = head;
node.next = new ListNode(1);
node = node.next;
node.next = new ListNode(2);
node = node.next;
node.next = new ListNode(3);
node = node.next;
node.next = new ListNode(3);
DeleteDuplicates solution = new DeleteDuplicates();
node = solution.deleteDuplicates(head);
solution.print(node);
}
private void print(ListNode node) {
for (; node != null; node = node.next) {
System.out.print(node.val);
System.out.print("->");
}
System.out.println("null");
}
public ListNode deleteDuplicates(ListNode head) {
ListNode node = head;
while (node != null) {
if (node.next != null && node.val == node.next.val)
node.next = node.next.next;
else
node = node.next;
}
return head;
}
}