题目地址:
https://www.lintcode.com/problem/remove-duplicates-from-sorted-list-ii/description
给定一个有序链表,要求删除其中出现多于一次的数字。
用前后双指针。前指针的作用是判断当前的数是否应该存在在最终答案里,如果应该,则加到答案链表的后面,否则前指针到duplicate的数字中的最后一个,即越过不应该存在在答案里的数,然后将其后面的数加进答案链表后面。代码如下:
public class Solution {
/**
* @param head: head is the head of the linked list
* @return: head of the linked list
*/
public ListNode deleteDuplicates(ListNode head) {
// write your code here
ListNode dummy = new ListNode(0);
ListNode prev = dummy, cur = head;
while (cur != null) {
// 如果cur之后是null或者cur的值等于其后的节点的值,那么说明cur应该加入最终结果;
if (cur.next == null || cur.val != cur.next.val) {
prev.next = cur;
prev = prev.next;
} else {
// 否则就说明有了重复数字,则将cur越过所有重复数字,将重复数字后一个节点连到prev后面
while (cur.next != null && cur.val == cur.next.val) {
cur = cur.next;
}
prev.next = cur.next;
}
// cur继续走一步,接着判断当前节点是否应该加入最终结果
cur = cur.next;
}
return dummy.next;
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
时间复杂度 O ( n ) O(n) O(n),空间 O ( 1 ) O(1) O(1)。