203. Remove Linked List Elements
unknown
plain_text
2 years ago
3.3 kB
21
Indexable
/**
* 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){
ListNode curr = head;
int length = 0;
while(curr != null){
length++;
curr = curr.next;
}
return length;
}
public static boolean areSame(Integer arr[])
{
// Put all array elements in a HashSet
Set<Integer> s = new HashSet<>(Arrays.asList(arr));
// If all elements are same, size of
// HashSet should be 1. As HashSet contains only distinct values.
return (s.size() == 1);
}
public ListNode removeElements(ListNode head, int val) {
int lenOfLL = lenLL(head);
Integer[] nums = new Integer[lenOfLL];
ListNode curr = head;
int i = 0;
while(curr != null){
nums[i] = curr.val;
i++;
curr = curr.next;
}
int valFrequency = 0;
for(int k = 0;k < nums.length;k++){
if(nums[k] == val){
valFrequency++;
}
else{
continue;
}
}
int[] valPositions = new int[valFrequency];
int p = 0;
for(int l = 0;l < nums.length;l++){
if(nums[l] == val){
valPositions[p] = l;
p++;
continue;
}
else{
continue;
}
}
System.out.println(Arrays.toString(valPositions));
//int j = 0;
//ListNode curr2 = head;
ListNode finalHead;
if(areSame(nums) && valFrequency != 0){
return null;
}
else if(valFrequency == 0){
return head;
}
else{
int j = 0;
ListNode curr2 = head;
ListNode curr3 = head;
for(int h = 0; h < valFrequency; h++){
while(curr2 != null){
if(valPositions[h] == 0){
curr2 = curr2.next;
if(curr3 != null)
curr3 = curr3.next;
j++;
head = head.next;
break;
}
if(j == valPositions[h] - 1){
if(curr3.next == null){
curr3 = curr3.next;
curr2.next = curr3;break;
}
else{
curr3 = curr3.next.next;
//curr2 = curr2.next;
curr2.next = curr3;
curr2 = curr2.next;
}
j+=2;
break;
}
else{
if(curr2 != null)
curr2 = curr2.next;
if(curr3 != null){
curr3 = curr3.next;
}
j++;
continue;
}
}
}
finalHead = head;
}
return finalHead;
}
}Editor is loading...