Last active
September 10, 2023 13:39
-
-
Save VEINHORN/063e231834fc7d7e962d7497698524bd to your computer and use it in GitHub Desktop.
Contains 2 resolved tasks for removing elements from Java's LinkedList
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
package com.veinhorn.playground; | |
import java.util.Arrays; | |
import java.util.Iterator; | |
import java.util.LinkedList; | |
import java.util.List; | |
public class Main { | |
public static void main(String[] args) { | |
removeAllEventNumbersFromLinkedList(); | |
System.out.println("\n"); | |
removeAllElementsAtUnevenPositions(); | |
} | |
private static void removeAllElementsAtUnevenPositions() { | |
List<Integer> list = new LinkedList<>(Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7)); | |
System.out.println("Input list: " + list); | |
Iterator<Integer> iterator = list.iterator(); | |
boolean isAtEvenPos = true; | |
while (iterator.hasNext()) { | |
iterator.next(); | |
if (!isAtEvenPos) { | |
iterator.remove(); | |
} | |
isAtEvenPos = !isAtEvenPos; | |
} | |
System.out.println("Output list: " + list); // we should get 0, 2, 4, 6 here | |
} | |
private static void removeAllEventNumbersFromLinkedList() { | |
List<Integer> list = new LinkedList<>(Arrays.asList(1, 2, 3, 4, 5, 6)); | |
System.out.println("Input list: " + list); | |
Iterator<Integer> iterator = list.iterator(); | |
while (iterator.hasNext()) { | |
if (iterator.next() % 2 == 0) iterator.remove(); | |
} | |
System.out.println("Output list: " + list); // we should get 1, 3, 5 here | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment