How to insert an element before the specified element in the linked list, so that the time complexity is n. For example I want to insert 100 before 7
LinkedList<Integer> linkedList = new LinkedList<>(); for (int i = 1; i <= 10; i++) { linkedList.add(i); } I can do it like this
int index = linkedList.indexOf(7); if (-1 != index) { linkedList.add(index, 100); } But I have traversed the linked list twice by this way. Actually we can do this just by traversing one time. So how can I do that?
PS:just use LinkedList
LinkedList.