/**82. Remove Duplicates from Sorted List II
* @param head
* @return 出现次数>=2的数字全不要
*/
public ListNode deleteDuplicates2(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode ret = new ListNode(-1);
ret.next = head;
ListNode pre = ret;
ListNode cur = pre.next;
ListNode post = cur.next;
boolean flag = false;
while (post != null) {
if (cur.val == post.val) {
flag = true;
post = post.next;
if (post == null) {
pre.next = null;
}
} else {
if (flag) {
pre.next = post;
flag = false;
} else {
pre = cur;
}
cur = post;
post = post.next;
}
}
return ret.next;
}
/**三个指针,pre cur post
* 引入一个布尔型的判断flag,来帮助判断当前是否遇到有重复,这个flag能帮助识别是否需要删除重复
* 当没有遇到重复值(flag为false)时,3个指针同时往后移动
* 当遇到重复值时,设置flag为true,并让post一直往后找找到第一个与cur值不等的位置时停止,
* 这时,cur指向的node的值是一个重复值,需要删除,所以这时就需要让pre的next连上当前的post,这样就把所有重复值略过了。
* 然后,让cur和post往后挪动继续查找。
* */
[LeeCode] 82. Remove Duplicates from Sorted List II java
最新推荐文章于 2019-02-12 05:00:23 发布