解题思路: 哨兵机制+三个指针
牛客地址
实现代码
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @return ListNode类
*/
public ListNode deleteDuplicates (ListNode head) {
// write code here
if(head == null || head.next == null){
return head;
}
ListNode dummy = new ListNode(-1);
ListNode p = dummy;
ListNode curPre = head;
ListNode cur = head;
while(cur != null){
while(cur != null && cur.val == curPre.val){
cur = cur.next;
}
p.next = curPre;
p = p.next;
curPre = cur;
}
//还是少了这里置为null的情况
p.next = null;
return dummy.next;
}
}
LeetCode
实现代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode dummy = new ListNode(-1);
ListNode p = dummy;
ListNode curPre = head;
ListNode cur = head;
while(cur != null){
while(cur != null && cur.val == curPre.val){
cur = cur.next;
}
//curPre为唯一节点,加入结果链表中
if(cur == curPre.next){
p.next = curPre;
p = p.next;
}
//[pre, cur) 之间的为重复节点,直接跳过
else{
curPre = cur;
}
}
p.next = null;//别忘了将链表尾置为null
return dummy.next;
}
}