对比删除有序链表中重复的元素-I,I是删除只留一个,II是重复就全删,前提都是升序链表。
这题top101中官方解答如下,但只用了一个cur指针,比较是否重复全用cur.next和cur.next.next,这样理解起来就不那么直观了,还是用两个指针会更好理解,故记录下自己写的版本,top101.pdf文档中绝大部分的题解还是十分详细且易懂的。
public class Solution {
public ListNode deleteDuplicates (ListNode head) {
// 直接比较删除法
if(head == null || head.next == null){
return head;//空或只有一个节点
}
//由于head节点就可能重复,故需要加头节点
ListNode res = new ListNode(-1);
res.next = head;
ListNode pre = res;
ListNode cur = head;
while(cur != null && cur.next != null){
if(cur.val == cur.next.val){
//跳过相同的元素
int temp = cur.val;
//前面是防止走到空还赋值
while(cur.next != null && temp == cur.next.val){
cur = cur.next;
}
pre.next = cur.next;//删除
cur = cur.next;//cur最后停在重复的最后一个,所以需要后移到下一个不重复的
}else{
//不相同,则正常后移
pre = cur;
cur = cur.next;
}
}
return res.next;
}
}



