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; * next = null; * } * } */ public class Solution { public ListNode deleteDuplicates(ListNode head) { // O(head, pre) -> O(cur) -> O if (head==null || head.next==null) return head; ListNode pre = head; ListNode cur = pre.next; while (cur != null) { if (pre.val != cur.val) { pre = pre.next; cur = cur.next; } else { while (cur!=null && cur.val==pre.val) cur = cur.next; pre.next = cur; pre = pre.next; if (cur != null) cur = cur.next; } } return head; } }
No comments:
Post a Comment