Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given
Given
Given
1->2->3->3->4->4->5
, return 1->2->5
.Given
1->1->1->2->3
, return 2->3
.
/**
* 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 p0 = new ListNode(0);
p0.next = head;
ListNode p1 = p0;
ListNode p2 = head;
while(true) {
if(p2!=null && p2.next!=null && p2.val==p2.next.val) {
while(p2.next!=null && p2.val==p2.next.val) {
p2 = p2.next;
}
p1.next = p2.next;
p2 = p1.next;
} else {
p1 = p2;
p2 = p2.next;
}
if(p2==null) {
break;
}
}
return p0.next;
}
}
======
/**
* 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 dummy = new ListNode(0);
ListNode p = dummy;
ListNode cur = head;
while (cur != null) {
if (cur.next != null && cur.val == cur.next.val) {
int val = cur.val;
while (cur != null && cur.val == val) {
cur = cur.next;
}
} else {
p.next = cur;
p = p.next;
cur = cur.next;
}
}
p.next = null;
return dummy.next;
}
}
======
/**
* 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 dummy = new ListNode(0);
ListNode p = dummy;
ListNode cur = head;
while (cur != null) {
if (cur.next != null && cur.val == cur.next.val) {
int val = cur.val;
while (cur != null && cur.val == val) {
cur = cur.next;
}
} else {
p.next = cur;
p = p.next;
cur = cur.next;
}
}
p.next = null;
return dummy.next;
}
}
没有评论:
发表评论