- They have a logical index, yes - effectively the number of times you need to iterate, starting from the head, before getting to that node.
- it can't directly search using index of the object
- 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.
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)); } }
Thursday, 29 November 2018
LinkedList and Index
About Unknown
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment