-1

can I cut (delete) a portion from a Linked List by index? For example, if the input is "100", I want to delete the first 100 elements from a linked list. Currently, my code deletes them one by one.

public void remove(LinkedList<String> queue, int count){
    if (count > queue.size()) {
        System.out.println(ERROR);
        return;
    }

    for (int i = 0; i < count; i++) {
        queue.remove(0);
    }
}
Tropicano
  • 281
  • 2
  • 15
  • No, there is no shortcut here - you must traverse the list to find the 100th element, so the time complexity is the same. You could skip deletion of every node and simply join the root the element 101 though. – Bohemian Nov 09 '19 at 21:05

2 Answers2

0

you try with this:

splitList =  queue.subList(0, 100);
0

To delete the first 100 elements of a List, whether ArrayList, LinkedList, or any other kind of mutable list:

list.subList(0, 100).clear();

This is documented in the javadoc of subList():

This method eliminates the need for explicit range operations (of the sort that commonly exist for arrays). Any operation that expects a list can be used as a range operation by passing a subList view instead of a whole list. For example, the following idiom removes a range of elements from a list:

list.subList(from, to).clear();
Community
  • 1
  • 1
Andreas
  • 154,647
  • 11
  • 152
  • 247