Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null)return head;
ListNode cur = head,start = head;
while(start != null){
if(cur == null){
start.next = null;
break;
}
if(cur.val == start.val)cur = cur.next;
else {
start.next = cur;
start = cur;
cur = cur.next;
}
}
return head;
}
}
/**
* 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 prev = new ListNode(-1);
ListNode curr = head;
while(curr != null) {
if(curr.val == prev.val) {
prev.next = curr.next;
} else {
prev = curr;
}
curr = curr.next;
}
return head;
}
}
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode curr=head;
while(curr!=null) {
ListNode temp=curr;
while(temp!=null && temp.val==curr.val) {
temp=temp.next;
}
curr.next=temp;
curr=curr.next;
}
return head;
}
}