← Java from Scratch Lesson 70 of 88 · 10 XP

LinkedList

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

LinkedList is a doubly linked list: each node knows the previous and the next one.

LinkedList<String> q = new LinkedList<>();
q.addFirst("a");   q.addLast("z");
q.getFirst();      q.getLast();
q.removeFirst();   q.removeLast();
q.poll();          // take and remove the first one (null if it's empty)
  • inserting and removing at the ends is O(1), but get(i) is O(n): you walk along the chain from an end;
  • it implements both List and Deque (a double-ended queue) — so it works as a queue and as a stack;
  • in practice ArrayDeque is more often used for a queue (it's faster), and LinkedList when you need to remove from the middle through an iterator.

Task. A counting-out game (the Josephus problem): n people stand in a circle, numbered 1…n; we count around the circle, and every k-th one is out. Use a LinkedList as a queue: "counting past" someone means moving the first one to the end (addLast(removeFirst())). Print the numbers in the order they're out.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.