双指针,不多说,代码如下:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 head; | |
ListNode sentinel = new ListNode(0); | |
sentinel.next = head; | |
ListNode ptr1 = sentinel, ptr2 = head; | |
int count = 0, base = head.val; | |
while (true) { | |
while (ptr2 != null && ptr2.val == base) { | |
count++; | |
ptr2 = ptr2.next; | |
} | |
if (count == 1) | |
ptr1 = ptr1.next; | |
ptr1.next = ptr2; | |
if (ptr2 == null) { | |
if (count > 1) | |
ptr1.next = null; | |
break; | |
} | |
count = 0; | |
base = ptr2.val; | |
} | |
return sentinel.next; | |
} | |
} |
No comments:
Post a Comment