Thursday, 29 November 2018

LinkedList and Index


  1. They have a logical index, yes - effectively the number of times you need to iterate, starting from the head, before getting to that node.
  2. it can't directly search using index of the object
  3. Typically O(1) access by index is performed by using an array lookup, and in the case of a linked list there isn't an array - there's just a chain of nodes. To access a node with index N, you need to start at the head and walk along the chain N times... which is an O(N) operation.
  4. import java.util.LinkedList; import java.util.List; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.IntStream; public class LnkedListNthh { public static void main(String[] args) { LnkedListNthh app = new LnkedListNthh(); LinkedList list = app.createList(); app.nthElement(list, 2); app.SecondLastElement(list); } private void nthElement(LinkedList list, Integer n) { list.get(n); System.out.println(n + "th Element is " + list.get(n)); } private void SecondLastElement(LinkedList list) { System.out.println("SecondLastElement = " + list.get(list.size() - 1)); } private LinkedList createList() { LinkedList list = new LinkedList(); Supplier> supplier = () -> new LinkedList(); return (LinkedList) IntStream.range(2, 102).boxed().collect(Collectors.toCollection(supplier)); } }

No comments:

Post a Comment

Search This Blog

Contact us

Name

Email *

Message *