For example,
Given
1->1->2
, return 1->2
.Given
1->1->2->3->3
, return 1->2->3
.
---
Solution: Iterate through the list. While the current node has the same value as the next node, remove the next node.
/**
* 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) {
ListNode cur = head;
while (cur != null) {
while (cur.next != null && cur.val == cur.next.val) {
cur.next = cur.next.next;
}
cur = cur.next;
}
return head;
}
}
No comments:
Post a Comment