题解 | #删除有序链表中重复的元素-II#
删除有序链表中重复的元素-II
http://www.nowcoder.com/practice/71cef9f8b5564579bf7ed93fbe0b2024
/*
* 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 dummyHead = new ListNode(-1);
dummyHead.next = head;
ListNode curr = dummyHead;
while(curr.next != null && curr.next.next != null) { // curr.next.val == curr.next.next.val要用到curr.next 和curr.next.next 因此这两个不能为null
if(curr.next.val == curr.next.next.val) {
int x = curr.next.val;
while(curr.next != null && curr.next.val == x) { // 删除多个元素 用循环实现
curr.next = curr.next.next;
}
}else {
curr = curr.next;
}
}
return dummyHead.next;
}
}