新博文地址:[leetcode]Remove Duplicates from Sorted List II
http://oj.leetcode.com/problems/remove-duplicates-from-sorted-list-ii/
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
我的想法还是很简单,遇到与后继节点相同的节点,就把其后驱节点删掉,并将该节点标记为should delete,时间复杂度为O(n),边界情况:当节点为最后一个节点时,应该找到其前驱节点。
我用了两种方法实现,一种不改变list结构,重新生成一个list,即空间复杂度O(n)
另一种直接在原list上进行操作,空间复杂度O(1)。
第一种:
public ListNode deleteDuplicates(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode tail = head;
List<Integer> list = new ArrayList<Integer>();
boolean delete = false;
while (tail != null) {
if (tail.next != null && tail.val != tail.next.val) {
if(!delete){
list.add(tail.val);
}else{
delete = false;
}
}else{
delete = true;
}
tail = tail.next;
if(tail.next == null){
if(!delete){
list.add(tail.val);
}
break;
}
}
ListNode newHead = new ListNode(0);
ListNode newTail = newHead;
for(Integer tem : list){
ListNode node = new ListNode(tem);
newTail.next = node;
newTail = node;
}
return newHead.next;
}
第二种:
public ListNode deleteDuplicates(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode tail = head;
boolean delete = false;
while (tail.next != null) {
if (tail.val == tail.next.val) {
delete = true;
tail.next = tail.next.next;
} else {
if (!delete) {
tail = tail.next;
} else {
tail.val = tail.next.val;
tail.next = tail.next.next;
delete = false;
}
}
}
ListNode tem = head;
if (delete) {
if (tail == head) {
return null;
} else {
while (tem.next != tail) {
tem = tem.next;
}
tem.next = null;
}
}
return head;
}
代码还是一如既往的长,不够简练啊。。。。囧