题目:https://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
.
算法分析:时间复杂度O(n),空间复杂度O(1)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head==null) {
return null;
}
ListNode newHead=new ListNode(0);
ListNode pre=null,node=head,newNode=newHead;
while(node!=null) {
if((pre==null || (pre!=null && pre.val!=node.val))
&& (node.next==null || (node.next!=null && node.val!=node.next.val))) {
newNode.next=node;
newNode=node;
}
pre=node;
node=node.next;
}
newNode.next=null;
return newHead.next;
}
}