Description
Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1:
Input: 1->1->2 Output: 1->2
Example 2:
Input: 1->1->2->3->3 Output: 1->2->3
Solution
Approach 1
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null)
return head;
ListNode pre = head, p = head;
while(p != null){
if(pre.val != p.val){
pre.next = p;
pre = p;
}
if(p.next == null){ //到了结尾,比较一下
if(p.val == pre.val) //相等pre就直接指向Null
pre.next = null;
}
p = p.next;
}
return head;
}
}
Approach 2 代码精简有力
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode current = head;
while(current != null && current.next != null){
if(current.val == current.next.val)
current.next = current.next.next; //current不变,next指向下一个
else
current = current.next; //不同则current移动
}
return head;
}
}