82. Remove Duplicates from Sorted List II
16-09-23 11:07AMunknown
plain_text
a year ago
2.0 kB
3
Indexable
Never
/** * 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 static int lenLL(ListNode head){ int len = 0; ListNode curr = head; while(curr != null){ len++; curr = curr.next; } return len; } public static ListNode deleteDuplicates(ListNode head) { ListNode curr = head; int lengthOfLL = lenLL(head); int[] numFrequency = new int[lengthOfLL]; int pos = 0; while (curr != null) { int count = 0; ListNode ptr2 = head; while (ptr2 != null) { if (curr.val == ptr2.val) { ptr2 = ptr2.next; count++; } else{ ptr2 = ptr2.next; continue; } } curr = curr.next; numFrequency[pos] = count; pos++; } // for (int i = 0; i < numFrequency.length; i++) { // System.out.print(numFrequency[i] + " "); // } // System.out.println(); ListNode curr2 = head; int pos2 = 0; ListNode dummy = new ListNode(); ListNode d = dummy; while(curr2 != null){ if(numFrequency[pos2] == 1){ ListNode temp = new ListNode(curr2.val); d.next = temp; d = d.next; d.next = null; curr2 = curr2.next; pos2++; } else{ curr2 = curr2.next; pos2++; continue; } } return dummy.next; } }