LeetCode OJ 82. Remove Duplicates from Sorted List II

时间:2023-03-09 12:54:43
LeetCode OJ 82. Remove Duplicates from Sorted List II

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

相对于Remove Duplicates from Sorted List这个问题,这个问题是要把重复出现过的所有元素全部删除。我的想法是找出每一个数字段的起点和终点,如果这个数据段出现了重复元素,就把这个数据段整体删除。

 public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head==null || head.next==null) return head;
ListNode thead = new ListNode(-1);
ListNode begin = thead;
ListNode end = head;
thead.next = head; int cur = head.val;
while(end.next!=null){
if(end.next.val==cur){
end = end.next;
}
else{
if(begin.next==end){
begin = end;
end = end.next;
}
else{
begin.next = end.next;
end = begin.next;
}
cur = end.val;
}
}
if(begin.next==end) return thead.next;
begin.next = null;
return thead.next;
}
}