Add linked-list module: singly and doubly lists with measured costs, reverse, middle, Floyd cycle detection, merge and 5 more interview problems, the 2015 menu programs and a doubly-list bug they exposed (15 tests, 15 transcripts)
Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b6r9iSyHu5qSJMzH2n
This commit is contained in:
@@ -32,6 +32,7 @@ One module per article. This repository currently holds:
|
|||||||
| [`food-delivery`](food-delivery/) | Low-Level Design: Food Delivery App (Zomato/Swiggy-Style) in Java | this commit |
|
| [`food-delivery`](food-delivery/) | Low-Level Design: Food Delivery App (Zomato/Swiggy-Style) in Java | this commit |
|
||||||
| [`binary-search`](binary-search/) | Binary Search in Java: Iterative, Recursive, Lower/Upper Bound and 10 Interview Problems | this commit |
|
| [`binary-search`](binary-search/) | Binary Search in Java: Iterative, Recursive, Lower/Upper Bound and 10 Interview Problems | this commit |
|
||||||
| [`notification-service`](notification-service/) | System Design: Notification Service with Spring Boot and Kafka (Email, SMS, Push) | this commit |
|
| [`notification-service`](notification-service/) | System Design: Notification Service with Spring Boot and Kafka (Email, SMS, Push) | this commit |
|
||||||
|
| [`linked-list`](linked-list/) | Linked List in Java: Singly, Doubly, Reverse, Cycle Detection and Interview Problems | this commit |
|
||||||
|
|
||||||
## `collections` module
|
## `collections` module
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,70 @@
|
|||||||
|
# linked-list
|
||||||
|
|
||||||
|
Companion code for the ankurm.com article **Linked List in Java: Singly, Doubly, Reverse, Cycle Detection and Interview Problems**
|
||||||
|
(a full rewrite of the 2015 posts "Implementing Singly Linked List in Java" and "Implementing Doubly Linked List in Java", now one article at the singly-list URL).
|
||||||
|
|
||||||
|
A singly and a doubly linked list built from scratch, with every operation's cost measured in links followed; then reverse, the middle node,
|
||||||
|
Floyd's cycle detection (and why its second phase works), merging sorted lists, remove-nth-from-end, palindrome, duplicates and intersection,
|
||||||
|
each cross-checked against an obviously-correct brute-force version on seeded random inputs. The two 2015 menu programs are kept and run
|
||||||
|
with the original keystrokes, which exposed a real bug in the 2015 doubly list. Every figure and console line in the article is quoted from a
|
||||||
|
file in `output/`, which the JUnit tests write while asserting the same numbers. There is no `docs/` folder: the explanations live in the article itself.
|
||||||
|
|
||||||
|
## Versions
|
||||||
|
|
||||||
|
| Component | Version | Verified against |
|
||||||
|
|---|---|---|
|
||||||
|
| JDK | Temurin 25.0.5.1+2 (LTS) | `java -version` |
|
||||||
|
| JUnit | 6.1.3 | latest GA on the junit-framework GitHub releases page; resolved from Maven Central by this build |
|
||||||
|
| Maven | 3.9.11 | `mvn -version` |
|
||||||
|
|
||||||
|
## Quickstart
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd linked-list
|
||||||
|
export JAVA_HOME=/path/to/jdk-25 PATH="$JAVA_HOME/bin:$PATH"
|
||||||
|
./scripts/run-all.sh # runs 15 tests and regenerates output/*.txt
|
||||||
|
java src/main/java/com/ankurm/interviewlab/linkedlist/LegacySinglyDemo.java # the 2015 singly list menu
|
||||||
|
java src/main/java/com/ankurm/interviewlab/linkedlist/LegacyDoublyDemo.java # the 2015 doubly list menu
|
||||||
|
```
|
||||||
|
|
||||||
|
The first Maven run must be online so the plugins land in the local cache.
|
||||||
|
|
||||||
|
## Source layout
|
||||||
|
|
||||||
|
```
|
||||||
|
linked-list/
|
||||||
|
├── pom.xml
|
||||||
|
├── scripts/run-all.sh
|
||||||
|
├── src/main/java/com/ankurm/interviewlab/linkedlist/
|
||||||
|
│ ├── ListNode.java value + next link; of(), withCycle(), show() that cannot hang on a cycle
|
||||||
|
│ ├── SinglyLinkedList.java addFirst/addLast/add/get/indexOf/remove*, with a hop counter and an optional tail pointer
|
||||||
|
│ ├── DoublyLinkedList.java next + prev links, O(1) addAfter/addBefore/remove(node), nodeAt from the nearer end
|
||||||
|
│ ├── LinkedListProblems.java reverse (2 ways), middle, hasCycle, cycleStart, cycleLength, merge, removeNth, palindrome, dedupe, intersection
|
||||||
|
│ ├── BruteForce.java slow, obviously-correct references (arrays, sorting, identity sets)
|
||||||
|
│ ├── DryRuns.java instrumented copies that record every step
|
||||||
|
│ ├── Pitfalls.java plausible-looking wrong versions
|
||||||
|
│ ├── LegacySinglyDemo.java the 2015 singly list menu program
|
||||||
|
│ └── LegacyDoublyDemo.java the 2015 doubly list menu program
|
||||||
|
├── src/test/java/.../ one test class per output file group
|
||||||
|
└── output/*.txt captured real output
|
||||||
|
```
|
||||||
|
|
||||||
|
## Captured output (`output/`)
|
||||||
|
|
||||||
|
| File | What it shows |
|
||||||
|
|---|---|
|
||||||
|
| `01-nodes-and-links.txt` | three nodes built by hand; inserting is one new object and one changed link |
|
||||||
|
| `02-singly-operations.txt` | every operation, the errors it throws, and the links each costs for n = 10 / 100 / 1000 |
|
||||||
|
| `03-delete-dry-run.txt` | the one pointer that changes when deleting from the middle, the head and the tail |
|
||||||
|
| `04-reverse-dry-run.txt` | three-pointer reversal pass by pass; recursion overflows the stack at 1,000,000 nodes |
|
||||||
|
| `05-middle-and-cycle.txt` | slow/fast pointers, a Floyd trace, and the meeting-point formulas checked on 930 shapes |
|
||||||
|
| `06-more-problems.txt` | merge trace, remove n-th from end, palindrome, duplicates, intersection |
|
||||||
|
| `07-doubly-list.txt` | both directions, O(1) unlink given a node, links followed from the nearer end |
|
||||||
|
| `08-legacy-bugs.txt` | the 2015 `insertAfter` never moved `last`: `deleteLast` removes the wrong node |
|
||||||
|
| `09-legacy-sentinel.txt` | the 2015 `removeFirst` returns 0 for both "removed a 0" and "list was empty" |
|
||||||
|
| `10-random-agreement.txt` | 400,000 seeded steps of both lists against `ArrayList`, 0 disagreements |
|
||||||
|
| `11-problems-agreement.txt` | 40,000 seeded cases of the interview problems against brute force, 0 disagreements |
|
||||||
|
| `12-pitfalls.txt` | five plausible mistakes, each run for real |
|
||||||
|
| `13-singly-session.txt` | the 2015 singly menu with the original keystrokes, identical to the 2015 sample output |
|
||||||
|
| `14-doubly-session.txt` | the 2015 doubly menu with the original keystrokes, identical to the 2015 sample output |
|
||||||
|
| `15-jdk-linkedlist.txt` | `java.util.LinkedList` is doubly linked, and `node(int)` starts from the nearer end (read from `lib/src.zip`) |
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
A linked list is nodes that point at each other
|
||||||
|
===============================================
|
||||||
|
|
||||||
|
a.val = 10 a.next.val = 20 a.next.next.val = 30 a.next.next.next = null
|
||||||
|
whole list from a: 10 -> 20 -> 30 -> null
|
||||||
|
length: 3
|
||||||
|
|
||||||
|
new node 15 points at 20: 15 -> 20 -> 30 -> null
|
||||||
|
a still reaches the old chain: 10 -> 20 -> 30 -> null
|
||||||
|
then a.next = the new node: 10 -> 15 -> 20 -> 30 -> null
|
||||||
|
one new object and one changed link; nothing else moved.
|
||||||
|
|
||||||
|
the empty list is null: ListNode.of() == null -> true
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
SinglyLinkedList: operations, errors and the links followed (hops)
|
||||||
|
==================================================================
|
||||||
|
|
||||||
|
addLast(10) -> [10]
|
||||||
|
addLast(30) -> [10, 30]
|
||||||
|
add(1, 20) -> [10, 20, 30]
|
||||||
|
addFirst(5) -> [5, 10, 20, 30]
|
||||||
|
remove(2) -> removed 20, list [5, 10, 30]
|
||||||
|
removeLast() -> removed 30, list [5, 10]
|
||||||
|
removeFirst() -> removed 5, list [10]
|
||||||
|
indexOf(10) -> 0 indexOf(99) -> -1
|
||||||
|
|
||||||
|
empty.removeFirst() throws NoSuchElementException: list is empty
|
||||||
|
list.get(5) throws IndexOutOfBoundsException: index 5, size 1
|
||||||
|
|
||||||
|
Links followed (hops) per operation, on a list that already holds n values:
|
||||||
|
n | addFirst | addLast no tail | addLast + tail | get(n/2) | indexOf(last) | removeFirst | removeLast
|
||||||
|
10 | 0 | 36 | 0 | 5 | 9 | 0 | 8
|
||||||
|
100 | 0 | 4851 | 0 | 50 | 99 | 0 | 98
|
||||||
|
1000 | 0 | 498501 | 0 | 500 | 999 | 0 | 998
|
||||||
|
("addLast no tail" and "addLast + tail" are the total hops to build the whole list of n by repeated addLast.)
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
Deleting from a singly linked list: which one pointer changes
|
||||||
|
=============================================================
|
||||||
|
|
||||||
|
remove the node at index 2 from 10 -> 20 -> 30 -> 40:
|
||||||
|
before: 10 -> 20 -> 30 -> 40 -> null
|
||||||
|
walk: before = node 20
|
||||||
|
found: before = 20, doomed = 30, doomed.next = 40
|
||||||
|
relink: 20.next = 40
|
||||||
|
after: 10 -> 20 -> 40 -> null
|
||||||
|
|
||||||
|
removing the head has no node before it, so the head variable itself changes:
|
||||||
|
before: head -> 10 -> 20 -> 30 -> null
|
||||||
|
head = head.next
|
||||||
|
after: head -> 20 -> 30 -> null
|
||||||
|
|
||||||
|
removing the tail needs the node before it, so it must be found by walking (and then tail moves back):
|
||||||
|
list 10, 20, 30, 40, 50: removeLast() returned 50 after following 3 links; list is now [10, 20, 30, 40]
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
Reversing 1 -> 2 -> 3 -> 4 with three pointers
|
||||||
|
==============================================
|
||||||
|
|
||||||
|
start prev=null cur=1 reversed: null still to do: 1 -> 2 -> 3 -> 4 -> null
|
||||||
|
pass 1 prev=1 cur=2 reversed: 1 -> null still to do: 2 -> 3 -> 4 -> null
|
||||||
|
pass 2 prev=2 cur=3 reversed: 2 -> 1 -> null still to do: 3 -> 4 -> null
|
||||||
|
pass 3 prev=3 cur=4 reversed: 3 -> 2 -> 1 -> null still to do: 4 -> null
|
||||||
|
pass 4 prev=4 cur=null reversed: 4 -> 3 -> 2 -> 1 -> null still to do: null
|
||||||
|
|
||||||
|
recursive version on the same list: 4 -> 3 -> 2 -> 1 -> null
|
||||||
|
|
||||||
|
iterative, 1,000,000 nodes: first value after reversing = 999999 (no problem)
|
||||||
|
recursive, 1,000 nodes on a 1 MB thread stack: ok
|
||||||
|
recursive, 1,000,000 nodes on a 1 MB thread stack: StackOverflowError
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
Middle node and cycle detection with a slow and a fast pointer
|
||||||
|
==============================================================
|
||||||
|
|
||||||
|
Middle node of 1 -> 2 -> ... -> n (for even n, the second of the two middles):
|
||||||
|
n = 1 -> middle value 1 (index 0)
|
||||||
|
n = 2 -> middle value 2 (index 1)
|
||||||
|
n = 3 -> middle value 2 (index 1)
|
||||||
|
n = 4 -> middle value 3 (index 2)
|
||||||
|
n = 5 -> middle value 3 (index 2)
|
||||||
|
n = 6 -> middle value 4 (index 3)
|
||||||
|
n = 7 -> middle value 4 (index 3)
|
||||||
|
n = 8 -> middle value 5 (index 4)
|
||||||
|
|
||||||
|
Floyd's algorithm on 3 -> 2 -> 0 -> -4 whose last node links back to index 1:
|
||||||
|
list: 3 -> 2 -> 0 -> -4 -> ... (last node links back to index 1)
|
||||||
|
step 0 slow at index 0 fast at index 0
|
||||||
|
step 1 slow at index 1 fast at index 2
|
||||||
|
step 2 slow at index 2 fast at index 1
|
||||||
|
step 3 slow at index 3 fast at index 3
|
||||||
|
they meet at index 3 after 3 steps: there is a cycle
|
||||||
|
phase 2: probe at index 0, slow at index 3
|
||||||
|
phase 2: probe at index 1, slow at index 1
|
||||||
|
they meet again at index 1 after 1 steps: that is where the cycle starts
|
||||||
|
|
||||||
|
cycleStart value = 2, cycleLength = 3, hasCycle = true
|
||||||
|
plain 3 -> 2 -> 0 -> -4: hasCycle = false, cycleStart = null, cycleLength = 0
|
||||||
|
|
||||||
|
Why the second phase works. Tail length mu (nodes before the cycle) and cycle length lambda:
|
||||||
|
mu lambda | steps until they meet | meet at index | phase-2 steps | cycle starts at index
|
||||||
|
0 4 | 4 | 0 | 0 | 0
|
||||||
|
1 10 | 10 | 10 | 1 | 1
|
||||||
|
3 4 | 4 | 4 | 3 | 3
|
||||||
|
4 4 | 4 | 4 | 4 | 4
|
||||||
|
5 4 | 8 | 8 | 5 | 5
|
||||||
|
7 3 | 9 | 9 | 7 | 7
|
||||||
|
30 30 | 30 | 30 | 30 | 30
|
||||||
|
checked all 930 combinations of mu = 0..30 and lambda = 1..30: the formulas held every time.
|
||||||
|
|
||||||
|
Memory: on a 100000-node ring, a set of seen nodes holds 100000 entries before it finds the repeat;
|
||||||
|
Floyd holds exactly two references (slow and fast) and reaches the same answer: hasCycle = true
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
Merge, remove n-th from end, palindrome, duplicates and intersection
|
||||||
|
====================================================================
|
||||||
|
|
||||||
|
Merge 1 -> 3 -> 5 and 2 -> 4 -> 6 -> 8 -> 9:
|
||||||
|
a: 1 -> 3 -> 5 -> null b: 2 -> 4 -> 6 -> 8 -> 9 -> null
|
||||||
|
compare 1 with 2 -> take 1 from a
|
||||||
|
merged so far: [1]
|
||||||
|
compare 3 with 2 -> take 2 from b
|
||||||
|
merged so far: [1, 2]
|
||||||
|
compare 3 with 4 -> take 3 from a
|
||||||
|
merged so far: [1, 2, 3]
|
||||||
|
compare 5 with 4 -> take 4 from b
|
||||||
|
merged so far: [1, 2, 3, 4]
|
||||||
|
compare 5 with 6 -> take 5 from a
|
||||||
|
merged so far: [1, 2, 3, 4, 5]
|
||||||
|
one list is empty; attach the rest of the other whole: 6 -> 8 -> 9 -> null
|
||||||
|
result: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 8 -> 9 -> null
|
||||||
|
|
||||||
|
Remove the n-th node from the end of 1 -> 2 -> 3 -> 4 -> 5:
|
||||||
|
n = 1 -> 1 -> 2 -> 3 -> 4 -> null
|
||||||
|
n = 2 -> 1 -> 2 -> 3 -> 5 -> null
|
||||||
|
n = 3 -> 1 -> 2 -> 4 -> 5 -> null
|
||||||
|
n = 4 -> 1 -> 3 -> 4 -> 5 -> null
|
||||||
|
n = 5 -> 2 -> 3 -> 4 -> 5 -> null
|
||||||
|
n = 4 on a 3-node list throws IllegalArgumentException: n = 4 is longer than the list
|
||||||
|
|
||||||
|
Palindrome check (the list is put back the way it was):
|
||||||
|
1 -> 2 -> 3 -> 2 -> 1 -> null -> true list afterwards: 1 -> 2 -> 3 -> 2 -> 1 -> null
|
||||||
|
1 -> 2 -> 2 -> 1 -> null -> true list afterwards: 1 -> 2 -> 2 -> 1 -> null
|
||||||
|
1 -> 2 -> 3 -> 4 -> null -> false list afterwards: 1 -> 2 -> 3 -> 4 -> null
|
||||||
|
7 -> null -> true list afterwards: 7 -> null
|
||||||
|
null -> true list afterwards: null
|
||||||
|
|
||||||
|
Remove duplicates from sorted 1 -> 1 -> 2 -> 3 -> 3 -> 3 -> 4 -> 4 -> null
|
||||||
|
-> 1 -> 2 -> 3 -> 4 -> null
|
||||||
|
|
||||||
|
Intersection: a = 4 -> 1 -> 8 -> 4 -> 5 -> null b = 5 -> 6 -> 1 -> 8 -> 4 -> 5 -> null (the 8 -> 4 -> 5 tail is one shared chain)
|
||||||
|
the lists join at the node holding 8; both 1s before it are different nodes with the same value
|
||||||
|
a list that merely has the same values 8 -> 4 -> 5 but its own nodes: intersection = null
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
DoublyLinkedList: two links per node, and what that buys
|
||||||
|
========================================================
|
||||||
|
|
||||||
|
addLast(20), addFirst(40), addLast(60)
|
||||||
|
forward (next links): [40, 20, 60]
|
||||||
|
backward (prev links): [60, 20, 40]
|
||||||
|
|
||||||
|
addAfter(node 20, 45) and addBefore(node 20, 65)
|
||||||
|
forward: [40, 65, 20, 45, 60]
|
||||||
|
backward: [60, 45, 20, 65, 40]
|
||||||
|
|
||||||
|
addAfter(the last node, 99): the tail has to move, and it does
|
||||||
|
forward: [40, 65, 20, 45, 60, 99]
|
||||||
|
backward: [99, 60, 45, 20, 65, 40]
|
||||||
|
last().val = 99, removeLast() returned 99
|
||||||
|
|
||||||
|
Links followed to reach one element of a 1000-element list:
|
||||||
|
index | doubly (nearer end) | singly (from head)
|
||||||
|
0 | 0 | 0
|
||||||
|
250 | 250 | 250
|
||||||
|
499 | 499 | 499
|
||||||
|
500 | 499 | 500
|
||||||
|
750 | 249 | 750
|
||||||
|
999 | 0 | 999
|
||||||
|
|
||||||
|
Unlinking the element at index 700 when you already hold the node:
|
||||||
|
doubly: 0 links followed (the node knows its neighbours)
|
||||||
|
singly: 699 links followed (it must walk to the node before it)
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
Two defects in the 2015 programs, reproduced
|
||||||
|
============================================
|
||||||
|
|
||||||
|
2015 DoublyLinkedList: insertAtLast(1), insertAtLast(2), insertAtLast(3), then insertAfter(4, position 3)
|
||||||
|
Forward: 1 2 3 4
|
||||||
|
Reverse: 3 2 1
|
||||||
|
last.data = 3 (the new node 4 is the real last node, but 'last' was never moved)
|
||||||
|
deleteLast() returned 3; forward now: Forward: 1 2
|
||||||
|
it should have removed only 4 and returned 4; instead both 3 and 4 are gone and the caller saw only the 3.
|
||||||
|
|
||||||
|
the DoublyLinkedList in this module, same operations:
|
||||||
|
forward: [1, 2, 3, 4]
|
||||||
|
backward: [4, 3, 2, 1]
|
||||||
|
removeLast() returned 4
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
removeFirst() on an empty list, 2015 version and this module
|
||||||
|
============================================================
|
||||||
|
|
||||||
|
2015 list holding the value 0: removeFirst() returned 0
|
||||||
|
2015 list that is empty: removeFirst() returned 0 (and printed: List is empty - nothing to remove)
|
||||||
|
A caller that only looks at the return value cannot tell these two cases apart.
|
||||||
|
this module, list holding 0: removeFirst() returned 0
|
||||||
|
this module, now empty: removeFirst() throws NoSuchElementException: list is empty
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
Seeded random operations, compared with java.util.ArrayList after every step
|
||||||
|
============================================================================
|
||||||
|
|
||||||
|
seed 2026, 2,000 sequences of 100 operations per class, each step compared with the reference
|
||||||
|
|
||||||
|
SinglyLinkedList 200,000 steps compared, 0 disagreements
|
||||||
|
DoublyLinkedList 200,000 steps compared (forward and backward), 0 disagreements
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
Every problem against an obviously-correct brute-force version on seeded random lists
|
||||||
|
=====================================================================================
|
||||||
|
|
||||||
|
seed 2026, 5,000 random cases per problem
|
||||||
|
|
||||||
|
problem cases disagreements
|
||||||
|
reverse (iterative, recursive) 5,000 0
|
||||||
|
middle 5,000 0
|
||||||
|
mergeSorted 5,000 0
|
||||||
|
removeNthFromEnd 5,000 0
|
||||||
|
isPalindrome 5,000 0
|
||||||
|
removeDuplicatesSorted 5,000 0
|
||||||
|
hasCycle / cycleStart / cycleLength 5,000 0
|
||||||
|
intersection 5,000 0
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
Five plausible mistakes, each run for real
|
||||||
|
==========================================
|
||||||
|
|
||||||
|
1. Reverse that reads cur.next after overwriting it, on 1 -> 2 -> 3 -> 4:
|
||||||
|
wrong: 1 -> null
|
||||||
|
correct: 4 -> 3 -> 2 -> 1 -> null
|
||||||
|
|
||||||
|
2. Remove the value 1 from 1 -> 2 -> 3, looking only one node ahead:
|
||||||
|
wrong: 1 -> 2 -> 3 -> null (nothing was removed, and no error)
|
||||||
|
with a dummy node in front: 2 -> 3 -> null
|
||||||
|
|
||||||
|
3. Cycle check that tests fast but not fast.next, on the plain list 1 -> 2 -> 3:
|
||||||
|
wrong: throws NullPointerException
|
||||||
|
correct: hasCycle = false
|
||||||
|
|
||||||
|
4. Merge that forgets to attach what is left, 1 -> 3 -> 5 and 2 -> 4 -> 6 -> 7 -> 8:
|
||||||
|
wrong: 1 -> 2 -> 3 -> 4 -> 5 -> null
|
||||||
|
correct: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> null
|
||||||
|
|
||||||
|
5. Comparing nodes by value when the question is about identity (the intersection problem):
|
||||||
|
two separate lists 8 -> 4 -> 5: same value at the head? true same node? false
|
||||||
|
|
||||||
|
Printing a list that has a cycle never ends, so ListNode.show stops after 12 nodes:
|
||||||
|
1 -> 2 -> 3 -> 2 -> 3 -> 2 -> 3 -> 2 -> 3 -> 2 -> 3 -> 2 -> ...
|
||||||
@@ -0,0 +1,176 @@
|
|||||||
|
The 2015 singly linked list menu program, same keystrokes as the original article
|
||||||
|
=================================================================================
|
||||||
|
|
||||||
|
keystrokes: 1 2 10 1 3 50 1 1 20 2 1 3 90 4 3 50 3 1 2 1 2 2 4 1 3 80 4 2 3 2 4 5
|
||||||
|
output identical to the 2015 article's sample output: true
|
||||||
|
|
||||||
|
--- Singly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Search
|
||||||
|
4. Display
|
||||||
|
5. Exit
|
||||||
|
Enter choice: 1
|
||||||
|
1. Insert at position
|
||||||
|
2. Insert at first
|
||||||
|
3. Insert at last
|
||||||
|
Enter choice: 2
|
||||||
|
Enter element: 10
|
||||||
|
|
||||||
|
--- Singly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Search
|
||||||
|
4. Display
|
||||||
|
5. Exit
|
||||||
|
Enter choice: 1
|
||||||
|
1. Insert at position
|
||||||
|
2. Insert at first
|
||||||
|
3. Insert at last
|
||||||
|
Enter choice: 3
|
||||||
|
Enter element: 50
|
||||||
|
|
||||||
|
--- Singly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Search
|
||||||
|
4. Display
|
||||||
|
5. Exit
|
||||||
|
Enter choice: 1
|
||||||
|
1. Insert at position
|
||||||
|
2. Insert at first
|
||||||
|
3. Insert at last
|
||||||
|
Enter choice: 1
|
||||||
|
Enter element: 20
|
||||||
|
Enter position: 2
|
||||||
|
|
||||||
|
--- Singly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Search
|
||||||
|
4. Display
|
||||||
|
5. Exit
|
||||||
|
Enter choice: 1
|
||||||
|
1. Insert at position
|
||||||
|
2. Insert at first
|
||||||
|
3. Insert at last
|
||||||
|
Enter choice: 3
|
||||||
|
Enter element: 90
|
||||||
|
|
||||||
|
--- Singly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Search
|
||||||
|
4. Display
|
||||||
|
5. Exit
|
||||||
|
Enter choice: 4
|
||||||
|
List: 10 20 50 90
|
||||||
|
|
||||||
|
--- Singly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Search
|
||||||
|
4. Display
|
||||||
|
5. Exit
|
||||||
|
Enter choice: 3
|
||||||
|
Enter element to search: 50
|
||||||
|
Element found at position: 3
|
||||||
|
|
||||||
|
--- Singly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Search
|
||||||
|
4. Display
|
||||||
|
5. Exit
|
||||||
|
Enter choice: 3
|
||||||
|
Enter element to search: 1
|
||||||
|
Element not found
|
||||||
|
|
||||||
|
--- Singly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Search
|
||||||
|
4. Display
|
||||||
|
5. Exit
|
||||||
|
Enter choice: 2
|
||||||
|
1. Remove first element
|
||||||
|
2. Remove last element
|
||||||
|
3. Remove element at position
|
||||||
|
Enter choice: 1
|
||||||
|
Removed: 10
|
||||||
|
|
||||||
|
--- Singly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Search
|
||||||
|
4. Display
|
||||||
|
5. Exit
|
||||||
|
Enter choice: 2
|
||||||
|
1. Remove first element
|
||||||
|
2. Remove last element
|
||||||
|
3. Remove element at position
|
||||||
|
Enter choice: 2
|
||||||
|
Removed: 90
|
||||||
|
|
||||||
|
--- Singly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Search
|
||||||
|
4. Display
|
||||||
|
5. Exit
|
||||||
|
Enter choice: 4
|
||||||
|
List: 20 50
|
||||||
|
|
||||||
|
--- Singly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Search
|
||||||
|
4. Display
|
||||||
|
5. Exit
|
||||||
|
Enter choice: 1
|
||||||
|
1. Insert at position
|
||||||
|
2. Insert at first
|
||||||
|
3. Insert at last
|
||||||
|
Enter choice: 3
|
||||||
|
Enter element: 80
|
||||||
|
|
||||||
|
--- Singly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Search
|
||||||
|
4. Display
|
||||||
|
5. Exit
|
||||||
|
Enter choice: 4
|
||||||
|
List: 20 50 80
|
||||||
|
|
||||||
|
--- Singly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Search
|
||||||
|
4. Display
|
||||||
|
5. Exit
|
||||||
|
Enter choice: 2
|
||||||
|
1. Remove first element
|
||||||
|
2. Remove last element
|
||||||
|
3. Remove element at position
|
||||||
|
Enter choice: 3
|
||||||
|
Enter position: 2
|
||||||
|
Removed: 50
|
||||||
|
|
||||||
|
--- Singly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Search
|
||||||
|
4. Display
|
||||||
|
5. Exit
|
||||||
|
Enter choice: 4
|
||||||
|
List: 20 80
|
||||||
|
|
||||||
|
--- Singly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Search
|
||||||
|
4. Display
|
||||||
|
5. Exit
|
||||||
|
Enter choice: 5
|
||||||
|
Exiting...
|
||||||
@@ -0,0 +1,184 @@
|
|||||||
|
The 2015 doubly linked list menu program, same keystrokes as the original article
|
||||||
|
=================================================================================
|
||||||
|
|
||||||
|
keystrokes: 1 1 20 1 1 40 1 2 60 1 3 45 2 1 4 65 2 3 1 3 2 2 1 2 2 3 1 4 20 2 3 2 3 1 5
|
||||||
|
output identical to the 2015 article's sample output: true
|
||||||
|
|
||||||
|
--- Doubly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Display list
|
||||||
|
4. Search
|
||||||
|
5. Exit
|
||||||
|
Select option: 1
|
||||||
|
1. Insert at first
|
||||||
|
2. Insert at last
|
||||||
|
3. Insert after position
|
||||||
|
4. Insert before position
|
||||||
|
Select: 1
|
||||||
|
Enter element: 20
|
||||||
|
|
||||||
|
--- Doubly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Display list
|
||||||
|
4. Search
|
||||||
|
5. Exit
|
||||||
|
Select option: 1
|
||||||
|
1. Insert at first
|
||||||
|
2. Insert at last
|
||||||
|
3. Insert after position
|
||||||
|
4. Insert before position
|
||||||
|
Select: 1
|
||||||
|
Enter element: 40
|
||||||
|
|
||||||
|
--- Doubly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Display list
|
||||||
|
4. Search
|
||||||
|
5. Exit
|
||||||
|
Select option: 1
|
||||||
|
1. Insert at first
|
||||||
|
2. Insert at last
|
||||||
|
3. Insert after position
|
||||||
|
4. Insert before position
|
||||||
|
Select: 2
|
||||||
|
Enter element: 60
|
||||||
|
|
||||||
|
--- Doubly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Display list
|
||||||
|
4. Search
|
||||||
|
5. Exit
|
||||||
|
Select option: 1
|
||||||
|
1. Insert at first
|
||||||
|
2. Insert at last
|
||||||
|
3. Insert after position
|
||||||
|
4. Insert before position
|
||||||
|
Select: 3
|
||||||
|
Enter element: 45
|
||||||
|
Enter position: 2
|
||||||
|
|
||||||
|
--- Doubly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Display list
|
||||||
|
4. Search
|
||||||
|
5. Exit
|
||||||
|
Select option: 1
|
||||||
|
1. Insert at first
|
||||||
|
2. Insert at last
|
||||||
|
3. Insert after position
|
||||||
|
4. Insert before position
|
||||||
|
Select: 4
|
||||||
|
Enter element: 65
|
||||||
|
Enter position: 2
|
||||||
|
|
||||||
|
--- Doubly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Display list
|
||||||
|
4. Search
|
||||||
|
5. Exit
|
||||||
|
Select option: 3
|
||||||
|
1. Forward display
|
||||||
|
2. Reverse display
|
||||||
|
Select: 1
|
||||||
|
Forward: 40 65 20 45 60
|
||||||
|
|
||||||
|
--- Doubly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Display list
|
||||||
|
4. Search
|
||||||
|
5. Exit
|
||||||
|
Select option: 3
|
||||||
|
1. Forward display
|
||||||
|
2. Reverse display
|
||||||
|
Select: 2
|
||||||
|
Reverse: 60 45 20 65 40
|
||||||
|
|
||||||
|
--- Doubly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Display list
|
||||||
|
4. Search
|
||||||
|
5. Exit
|
||||||
|
Select option: 2
|
||||||
|
1. Delete first
|
||||||
|
2. Delete last
|
||||||
|
3. Delete at position
|
||||||
|
Select: 1
|
||||||
|
Deleted: 40
|
||||||
|
|
||||||
|
--- Doubly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Display list
|
||||||
|
4. Search
|
||||||
|
5. Exit
|
||||||
|
Select option: 2
|
||||||
|
1. Delete first
|
||||||
|
2. Delete last
|
||||||
|
3. Delete at position
|
||||||
|
Select: 2
|
||||||
|
Deleted: 60
|
||||||
|
|
||||||
|
--- Doubly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Display list
|
||||||
|
4. Search
|
||||||
|
5. Exit
|
||||||
|
Select option: 3
|
||||||
|
1. Forward display
|
||||||
|
2. Reverse display
|
||||||
|
Select: 1
|
||||||
|
Forward: 65 20 45
|
||||||
|
|
||||||
|
--- Doubly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Display list
|
||||||
|
4. Search
|
||||||
|
5. Exit
|
||||||
|
Select option: 4
|
||||||
|
Enter element to search: 20
|
||||||
|
Element found at position: 2
|
||||||
|
|
||||||
|
--- Doubly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Display list
|
||||||
|
4. Search
|
||||||
|
5. Exit
|
||||||
|
Select option: 2
|
||||||
|
1. Delete first
|
||||||
|
2. Delete last
|
||||||
|
3. Delete at position
|
||||||
|
Select: 3
|
||||||
|
Enter position: 2
|
||||||
|
Deleted: 20
|
||||||
|
|
||||||
|
--- Doubly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Display list
|
||||||
|
4. Search
|
||||||
|
5. Exit
|
||||||
|
Select option: 3
|
||||||
|
1. Forward display
|
||||||
|
2. Reverse display
|
||||||
|
Select: 1
|
||||||
|
Forward: 65 45
|
||||||
|
|
||||||
|
--- Doubly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Display list
|
||||||
|
4. Search
|
||||||
|
5. Exit
|
||||||
|
Select option: 5
|
||||||
|
Exiting...
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
java.util.LinkedList, read from this JDK
|
||||||
|
========================================
|
||||||
|
|
||||||
|
JDK: 25.0.5.1+2-LTS
|
||||||
|
|
||||||
|
fields of java.util.LinkedList$Node (reflection): [Node next, Node prev, Object item]
|
||||||
|
interfaces of java.util.LinkedList: [List, Deque, Cloneable, Serializable]
|
||||||
|
|
||||||
|
java/util/LinkedList.java, node(int index), from line 578:
|
||||||
|
578 Node<E> node(int index) {
|
||||||
|
579 // assert isElementIndex(index);
|
||||||
|
580
|
||||||
|
581 if (index < (size >> 1)) {
|
||||||
|
582 Node<E> x = first;
|
||||||
|
583 for (int i = 0; i < index; i++)
|
||||||
|
584 x = x.next;
|
||||||
|
585 return x;
|
||||||
|
586 } else {
|
||||||
|
587 Node<E> x = last;
|
||||||
|
588 for (int i = size - 1; i > index; i--)
|
||||||
|
589 x = x.prev;
|
||||||
|
590 return x;
|
||||||
|
591 }
|
||||||
|
592 }
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<groupId>com.ankurm.interviewlab</groupId>
|
||||||
|
<artifactId>linked-list</artifactId>
|
||||||
|
<version>1.0.0</version>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
|
<name>java-interview-lab :: linked-list</name>
|
||||||
|
<description>
|
||||||
|
Runnable companion code for ankurm.com's "Linked List in Java" article: singly and doubly linked lists, reverse, middle node, Floyd cycle detection, merge two lists and more interview problems, each cross-checked against a brute-force version.
|
||||||
|
</description>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<maven.compiler.release>25</maven.compiler.release>
|
||||||
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
|
<junit.version>6.1.3</junit.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
<dependencyManagement>
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit</groupId>
|
||||||
|
<artifactId>junit-bom</artifactId>
|
||||||
|
<version>${junit.version}</version>
|
||||||
|
<type>pom</type>
|
||||||
|
<scope>import</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
</dependencyManagement>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.jupiter</groupId>
|
||||||
|
<artifactId>junit-jupiter</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.platform</groupId>
|
||||||
|
<artifactId>junit-platform-launcher</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>3.14.0</version>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
|
<version>3.6.0</version>
|
||||||
|
<configuration>
|
||||||
|
<argLine>-Xmx512m -Duser.timezone=UTC -Dfile.encoding=UTF-8</argLine>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</project>
|
||||||
Executable
+9
@@ -0,0 +1,9 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Regenerates every file in output/. Needs JDK 25 and Maven. The first Maven run must be online.
|
||||||
|
# Every file is written by a JUnit test that asserts the same numbers it prints, so the figures
|
||||||
|
# in the article are assertions: they fail the build the moment they stop being true.
|
||||||
|
set -euo pipefail
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
mkdir -p output
|
||||||
|
mvn -B -q -T1 test
|
||||||
|
echo "done:"; ls -1 output
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
package com.ankurm.interviewlab.linkedlist;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.IdentityHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
/** Slow, obviously-correct references that share no code with LinkedListProblems: arrays, sorting and identity sets. */
|
||||||
|
public final class BruteForce {
|
||||||
|
private BruteForce() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int[] reverse(int[] values) {
|
||||||
|
int[] out = new int[values.length];
|
||||||
|
for (int i = 0; i < values.length; i++) {
|
||||||
|
out[i] = values[values.length - 1 - i];
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Index of the middle node (second middle for even length). */
|
||||||
|
public static int middleIndex(int length) {
|
||||||
|
return length / 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean hasCycle(ListNode head) {
|
||||||
|
return cycleStart(head) != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Walk with a set of nodes already seen; the first node seen twice starts the cycle. */
|
||||||
|
public static ListNode cycleStart(ListNode head) {
|
||||||
|
Set<ListNode> seen = Collections.newSetFromMap(new IdentityHashMap<>());
|
||||||
|
for (ListNode cur = head; cur != null; cur = cur.next) {
|
||||||
|
if (!seen.add(cur)) {
|
||||||
|
return cur;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int[] mergeSorted(int[] a, int[] b) {
|
||||||
|
int[] all = new int[a.length + b.length];
|
||||||
|
System.arraycopy(a, 0, all, 0, a.length);
|
||||||
|
System.arraycopy(b, 0, all, a.length, b.length);
|
||||||
|
Arrays.sort(all);
|
||||||
|
return all;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int[] removeNthFromEnd(int[] values, int n) {
|
||||||
|
List<Integer> list = new ArrayList<>();
|
||||||
|
for (int v : values) {
|
||||||
|
list.add(v);
|
||||||
|
}
|
||||||
|
list.remove(values.length - n);
|
||||||
|
return list.stream().mapToInt(Integer::intValue).toArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean isPalindrome(int[] values) {
|
||||||
|
return Arrays.equals(values, reverse(values));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int[] removeDuplicatesSorted(int[] sortedValues) {
|
||||||
|
return Arrays.stream(sortedValues).distinct().toArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static ListNode intersection(ListNode a, ListNode b) {
|
||||||
|
Set<ListNode> inA = Collections.newSetFromMap(new IdentityHashMap<>());
|
||||||
|
for (ListNode cur = a; cur != null; cur = cur.next) {
|
||||||
|
inA.add(cur);
|
||||||
|
}
|
||||||
|
for (ListNode cur = b; cur != null; cur = cur.next) {
|
||||||
|
if (inA.contains(cur)) {
|
||||||
|
return cur;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,217 @@
|
|||||||
|
package com.ankurm.interviewlab.linkedlist;
|
||||||
|
|
||||||
|
import java.util.NoSuchElementException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A doubly linked list of ints: every node knows both neighbours, so a node that has been found can be
|
||||||
|
* unlinked or have a neighbour added in O(1). Counts the links it follows in {@code hops}.
|
||||||
|
*/
|
||||||
|
public final class DoublyLinkedList {
|
||||||
|
/** A node with a link each way. Callers may hold on to a Node to act on it later in O(1). */
|
||||||
|
public static final class Node {
|
||||||
|
public int val;
|
||||||
|
private Node prev;
|
||||||
|
private Node next;
|
||||||
|
|
||||||
|
Node(int val) {
|
||||||
|
this.val = val;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Node prev() {
|
||||||
|
return prev;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Node next() {
|
||||||
|
return next;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Node head;
|
||||||
|
private Node tail;
|
||||||
|
private int size;
|
||||||
|
private long hops;
|
||||||
|
|
||||||
|
public int size() {
|
||||||
|
return size;
|
||||||
|
}
|
||||||
|
|
||||||
|
public long hops() {
|
||||||
|
return hops;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void resetHops() {
|
||||||
|
hops = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Node first() {
|
||||||
|
return head;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Node last() {
|
||||||
|
return tail;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Node addFirst(int value) {
|
||||||
|
Node node = new Node(value);
|
||||||
|
node.next = head;
|
||||||
|
if (head != null) {
|
||||||
|
head.prev = node;
|
||||||
|
} else {
|
||||||
|
tail = node;
|
||||||
|
}
|
||||||
|
head = node;
|
||||||
|
size++;
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Node addLast(int value) {
|
||||||
|
Node node = new Node(value);
|
||||||
|
node.prev = tail;
|
||||||
|
if (tail != null) {
|
||||||
|
tail.next = node;
|
||||||
|
} else {
|
||||||
|
head = node;
|
||||||
|
}
|
||||||
|
tail = node;
|
||||||
|
size++;
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Four pointer writes. The else branch is the one the 2015 insertAfter forgot. */
|
||||||
|
public Node addAfter(Node node, int value) {
|
||||||
|
Node added = new Node(value);
|
||||||
|
added.prev = node;
|
||||||
|
added.next = node.next;
|
||||||
|
if (node.next != null) {
|
||||||
|
node.next.prev = added;
|
||||||
|
} else {
|
||||||
|
tail = added;
|
||||||
|
}
|
||||||
|
node.next = added;
|
||||||
|
size++;
|
||||||
|
return added;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Node addBefore(Node node, int value) {
|
||||||
|
Node added = new Node(value);
|
||||||
|
added.next = node;
|
||||||
|
added.prev = node.prev;
|
||||||
|
if (node.prev != null) {
|
||||||
|
node.prev.next = added;
|
||||||
|
} else {
|
||||||
|
head = added;
|
||||||
|
}
|
||||||
|
node.prev = added;
|
||||||
|
size++;
|
||||||
|
return added;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Unlinks a node in O(1) because it already knows both neighbours. */
|
||||||
|
public int remove(Node node) {
|
||||||
|
if (node.prev != null) {
|
||||||
|
node.prev.next = node.next;
|
||||||
|
} else {
|
||||||
|
head = node.next;
|
||||||
|
}
|
||||||
|
if (node.next != null) {
|
||||||
|
node.next.prev = node.prev;
|
||||||
|
} else {
|
||||||
|
tail = node.prev;
|
||||||
|
}
|
||||||
|
node.prev = null;
|
||||||
|
node.next = null;
|
||||||
|
size--;
|
||||||
|
return node.val;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int removeFirst() {
|
||||||
|
if (head == null) {
|
||||||
|
throw new NoSuchElementException("list is empty");
|
||||||
|
}
|
||||||
|
return remove(head);
|
||||||
|
}
|
||||||
|
|
||||||
|
public int removeLast() {
|
||||||
|
if (tail == null) {
|
||||||
|
throw new NoSuchElementException("list is empty");
|
||||||
|
}
|
||||||
|
return remove(tail);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Starts from whichever end is closer, so it follows at most size / 2 links. */
|
||||||
|
public Node nodeAt(int index) {
|
||||||
|
if (index < 0 || index >= size) {
|
||||||
|
throw new IndexOutOfBoundsException("index " + index + ", size " + size);
|
||||||
|
}
|
||||||
|
Node cur;
|
||||||
|
if (index < size / 2) {
|
||||||
|
cur = head;
|
||||||
|
for (int i = 0; i < index; i++) {
|
||||||
|
cur = cur.next;
|
||||||
|
hops++;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
cur = tail;
|
||||||
|
for (int i = size - 1; i > index; i--) {
|
||||||
|
cur = cur.prev;
|
||||||
|
hops++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return cur;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int get(int index) {
|
||||||
|
return nodeAt(index).val;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Inserts so that the new value ends up at {@code index}; index == size() appends. */
|
||||||
|
public void add(int index, int value) {
|
||||||
|
if (index < 0 || index > size) {
|
||||||
|
throw new IndexOutOfBoundsException("index " + index + ", size " + size);
|
||||||
|
}
|
||||||
|
if (index == size) {
|
||||||
|
addLast(value);
|
||||||
|
} else {
|
||||||
|
addBefore(nodeAt(index), value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public int remove(int index) {
|
||||||
|
return remove(nodeAt(index));
|
||||||
|
}
|
||||||
|
|
||||||
|
public int[] toArray() {
|
||||||
|
int[] out = new int[size];
|
||||||
|
int i = 0;
|
||||||
|
for (Node cur = head; cur != null; cur = cur.next) {
|
||||||
|
out[i++] = cur.val;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The same values read from the tail with the prev links. */
|
||||||
|
public int[] toArrayReversed() {
|
||||||
|
int[] out = new int[size];
|
||||||
|
int i = 0;
|
||||||
|
for (Node cur = tail; cur != null; cur = cur.prev) {
|
||||||
|
out[i++] = cur.val;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String show(int[] values) {
|
||||||
|
StringBuilder sb = new StringBuilder("[");
|
||||||
|
for (int i = 0; i < values.length; i++) {
|
||||||
|
sb.append(values[i]);
|
||||||
|
if (i < values.length - 1) {
|
||||||
|
sb.append(", ");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return sb.append("]").toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return show(toArray());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
package com.ankurm.interviewlab.linkedlist;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/** Instrumented copies of the algorithms that record every step, so the article can show the pointers moving. */
|
||||||
|
public final class DryRuns {
|
||||||
|
private DryRuns() {
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String v(ListNode n) {
|
||||||
|
return n == null ? "null" : String.valueOf(n.val);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Reverse a list of the given values, one line per loop pass. */
|
||||||
|
public static List<String> reverse(int... values) {
|
||||||
|
List<String> lines = new ArrayList<>();
|
||||||
|
ListNode prev = null;
|
||||||
|
ListNode cur = ListNode.of(values);
|
||||||
|
lines.add(String.format("start prev=%-4s cur=%-4s reversed: %-26s still to do: %s",
|
||||||
|
v(prev), v(cur), ListNode.show(prev), ListNode.show(cur)));
|
||||||
|
int step = 1;
|
||||||
|
while (cur != null) {
|
||||||
|
ListNode next = cur.next;
|
||||||
|
cur.next = prev;
|
||||||
|
prev = cur;
|
||||||
|
cur = next;
|
||||||
|
lines.add(String.format("pass %-3d prev=%-4s cur=%-4s reversed: %-26s still to do: %s",
|
||||||
|
step++, v(prev), v(cur), ListNode.show(prev), ListNode.show(cur)));
|
||||||
|
}
|
||||||
|
return lines;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Remove the node at index (>= 1) from a list, showing the one pointer that changes. */
|
||||||
|
public static List<String> removeAt(int index, int... values) {
|
||||||
|
List<String> lines = new ArrayList<>();
|
||||||
|
ListNode head = ListNode.of(values);
|
||||||
|
lines.add("before: " + ListNode.show(head));
|
||||||
|
ListNode before = head;
|
||||||
|
for (int i = 0; i < index - 1; i++) {
|
||||||
|
before = before.next;
|
||||||
|
lines.add("walk: before = node " + before.val);
|
||||||
|
}
|
||||||
|
ListNode doomed = before.next;
|
||||||
|
lines.add(String.format("found: before = %d, doomed = %d, doomed.next = %s", before.val, doomed.val, v(doomed.next)));
|
||||||
|
before.next = doomed.next;
|
||||||
|
lines.add(String.format("relink: %d.next = %s", before.val, v(before.next)));
|
||||||
|
lines.add("after: " + ListNode.show(head));
|
||||||
|
return lines;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Floyd's algorithm on a list with a tail that links back to cycleAt, one line per step. */
|
||||||
|
public static List<String> floyd(int[] values, int cycleAt) {
|
||||||
|
List<String> lines = new ArrayList<>();
|
||||||
|
ListNode[] nodes = new ListNode[values.length];
|
||||||
|
for (int i = 0; i < values.length; i++) {
|
||||||
|
nodes[i] = new ListNode(values[i]);
|
||||||
|
if (i > 0) {
|
||||||
|
nodes[i - 1].next = nodes[i];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
nodes[values.length - 1].next = nodes[cycleAt];
|
||||||
|
lines.add("list: " + ListNode.show(nodes[0], values.length) + " (last node links back to index " + cycleAt + ")");
|
||||||
|
ListNode slow = nodes[0];
|
||||||
|
ListNode fast = nodes[0];
|
||||||
|
int step = 0;
|
||||||
|
lines.add(String.format("step %-2d slow at index %d fast at index %d", step, indexOf(nodes, slow), indexOf(nodes, fast)));
|
||||||
|
while (true) {
|
||||||
|
slow = slow.next;
|
||||||
|
fast = fast.next.next;
|
||||||
|
step++;
|
||||||
|
lines.add(String.format("step %-2d slow at index %d fast at index %d", step, indexOf(nodes, slow), indexOf(nodes, fast)));
|
||||||
|
if (slow == fast) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
lines.add("they meet at index " + indexOf(nodes, slow) + " after " + step + " steps: there is a cycle");
|
||||||
|
ListNode probe = nodes[0];
|
||||||
|
int walked = 0;
|
||||||
|
lines.add(String.format("phase 2: probe at index %d, slow at index %d", indexOf(nodes, probe), indexOf(nodes, slow)));
|
||||||
|
while (probe != slow) {
|
||||||
|
probe = probe.next;
|
||||||
|
slow = slow.next;
|
||||||
|
walked++;
|
||||||
|
lines.add(String.format("phase 2: probe at index %d, slow at index %d", indexOf(nodes, probe), indexOf(nodes, slow)));
|
||||||
|
}
|
||||||
|
lines.add("they meet again at index " + indexOf(nodes, probe) + " after " + walked + " steps: that is where the cycle starts");
|
||||||
|
return lines;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Merge two sorted lists, one line per comparison. */
|
||||||
|
public static List<String> merge(int[] a, int[] b) {
|
||||||
|
List<String> lines = new ArrayList<>();
|
||||||
|
ListNode x = ListNode.of(a);
|
||||||
|
ListNode y = ListNode.of(b);
|
||||||
|
ListNode dummy = new ListNode(0);
|
||||||
|
ListNode tail = dummy;
|
||||||
|
lines.add("a: " + ListNode.show(x) + " b: " + ListNode.show(y));
|
||||||
|
List<Integer> taken = new ArrayList<>();
|
||||||
|
while (x != null && y != null) {
|
||||||
|
boolean takeA = x.val <= y.val;
|
||||||
|
lines.add(String.format("compare %d with %d -> take %d from %s", x.val, y.val, takeA ? x.val : y.val, takeA ? "a" : "b"));
|
||||||
|
taken.add(takeA ? x.val : y.val);
|
||||||
|
if (takeA) {
|
||||||
|
tail.next = x;
|
||||||
|
x = x.next;
|
||||||
|
} else {
|
||||||
|
tail.next = y;
|
||||||
|
y = y.next;
|
||||||
|
}
|
||||||
|
tail = tail.next;
|
||||||
|
lines.add(" merged so far: " + taken);
|
||||||
|
}
|
||||||
|
tail.next = (x != null) ? x : y;
|
||||||
|
lines.add("one list is empty; attach the rest of the other whole: " + ListNode.show(tail.next));
|
||||||
|
lines.add("result: " + ListNode.show(dummy.next));
|
||||||
|
return lines;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int indexOf(ListNode[] nodes, ListNode node) {
|
||||||
|
for (int i = 0; i < nodes.length; i++) {
|
||||||
|
if (nodes[i] == node) {
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,301 @@
|
|||||||
|
package com.ankurm.interviewlab.linkedlist;
|
||||||
|
|
||||||
|
import java.io.BufferedReader;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStreamReader;
|
||||||
|
import java.io.PrintStream;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The program from the 2015 article "Implementing Doubly Linked List in Java", kept as it was so the new article can run it and
|
||||||
|
* measure it. The list logic is unchanged. Only two things moved: the classes became inner classes, and
|
||||||
|
* output goes through a PrintStream (instead of System.out) so a test can capture the session.
|
||||||
|
*/
|
||||||
|
public class LegacyDoublyDemo {
|
||||||
|
private final PrintStream out;
|
||||||
|
|
||||||
|
public LegacyDoublyDemo(PrintStream out) {
|
||||||
|
this.out = out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A single node in the doubly linked list
|
||||||
|
class DLLNode {
|
||||||
|
int data;
|
||||||
|
DLLNode prev; // Pointer to the previous node
|
||||||
|
DLLNode next; // Pointer to the next node
|
||||||
|
|
||||||
|
public DLLNode() {
|
||||||
|
prev = next = null;
|
||||||
|
data = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Doubly Linked List with full insertion, deletion, search, and display
|
||||||
|
class DoublyLinkedList {
|
||||||
|
DLLNode start; // First node in the list
|
||||||
|
DLLNode last; // Last node in the list
|
||||||
|
DLLNode current; // Helper pointer for traversal
|
||||||
|
|
||||||
|
// Creates the first node when the list is empty
|
||||||
|
private void createList(int value) {
|
||||||
|
DLLNode newNode = new DLLNode();
|
||||||
|
newNode.data = value;
|
||||||
|
start = last = newNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Inserts a new node at the beginning of the list
|
||||||
|
public void insertAtFirst(int value) {
|
||||||
|
if (start == null) {
|
||||||
|
createList(value);
|
||||||
|
} else {
|
||||||
|
DLLNode newNode = new DLLNode();
|
||||||
|
newNode.data = value;
|
||||||
|
start.prev = newNode; // Old start's prev now points to new node
|
||||||
|
newNode.next = start; // New node's next points to old start
|
||||||
|
start = newNode; // Update start to new node
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Inserts a new node at the end of the list
|
||||||
|
public void insertAtLast(int value) {
|
||||||
|
if (start == null) {
|
||||||
|
createList(value);
|
||||||
|
} else {
|
||||||
|
DLLNode newNode = new DLLNode();
|
||||||
|
newNode.data = value;
|
||||||
|
last.next = newNode; // Old last's next points to new node
|
||||||
|
newNode.prev = last; // New node's prev points to old last
|
||||||
|
last = newNode; // Update last to new node
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Inserts a new node after the node at the given 1-based position
|
||||||
|
public void insertAfter(int value, int position) {
|
||||||
|
if (start == null) {
|
||||||
|
createList(value);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (position <= 0) {
|
||||||
|
out.println("Invalid position");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
int index = 1;
|
||||||
|
current = start;
|
||||||
|
while (current != null) {
|
||||||
|
if (index == position) {
|
||||||
|
DLLNode newNode = new DLLNode();
|
||||||
|
newNode.data = value;
|
||||||
|
newNode.next = current.next;
|
||||||
|
if (current.next != null) current.next.prev = newNode;
|
||||||
|
newNode.prev = current;
|
||||||
|
current.next = newNode;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
current = current.next;
|
||||||
|
index++;
|
||||||
|
}
|
||||||
|
out.println("Position out of range");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Inserts a new node before the node at the given 1-based position
|
||||||
|
public void insertBefore(int value, int position) {
|
||||||
|
if (start == null) {
|
||||||
|
createList(value);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (position <= 1) {
|
||||||
|
insertAtFirst(value);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
int index = 1;
|
||||||
|
current = start;
|
||||||
|
while (current != null) {
|
||||||
|
if (index == position - 1) {
|
||||||
|
DLLNode newNode = new DLLNode();
|
||||||
|
newNode.data = value;
|
||||||
|
newNode.next = current.next;
|
||||||
|
if (current.next != null) current.next.prev = newNode;
|
||||||
|
newNode.prev = current;
|
||||||
|
current.next = newNode;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
current = current.next;
|
||||||
|
index++;
|
||||||
|
}
|
||||||
|
out.println("Position out of range");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Searches for a value and returns its 1-based position, or -1 if not found
|
||||||
|
public int search(int value) {
|
||||||
|
current = start;
|
||||||
|
int position = 1;
|
||||||
|
while (current != null) {
|
||||||
|
if (current.data == value) return position;
|
||||||
|
current = current.next;
|
||||||
|
position++;
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Displays the list from start to end (forward direction)
|
||||||
|
public void displayForward() {
|
||||||
|
current = start;
|
||||||
|
out.print("Forward: ");
|
||||||
|
while (current != null) {
|
||||||
|
out.print(current.data + " ");
|
||||||
|
current = current.next;
|
||||||
|
}
|
||||||
|
out.println();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Displays the list from end to start (reverse direction)
|
||||||
|
public void displayReverse() {
|
||||||
|
current = last;
|
||||||
|
out.print("Reverse: ");
|
||||||
|
while (current != null) {
|
||||||
|
out.print(current.data + " ");
|
||||||
|
current = current.prev;
|
||||||
|
}
|
||||||
|
out.println();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Removes and returns the first node's value
|
||||||
|
public int deleteFirst() {
|
||||||
|
if (start == null) {
|
||||||
|
out.println("List is empty");
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
int value = start.data;
|
||||||
|
start = start.next;
|
||||||
|
if (start != null) start.prev = null;
|
||||||
|
else last = null;
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Removes and returns the last node's value
|
||||||
|
public int deleteLast() {
|
||||||
|
if (start == null) {
|
||||||
|
out.println("List is empty");
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
int value = last.data;
|
||||||
|
if (last.prev != null) {
|
||||||
|
last.prev.next = null;
|
||||||
|
last = last.prev;
|
||||||
|
} else {
|
||||||
|
start = last = null;
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Removes and returns the node at the given 1-based position
|
||||||
|
public int deleteAt(int position) {
|
||||||
|
if (start == null) {
|
||||||
|
out.println("List is empty");
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
if (position <= 0) {
|
||||||
|
out.println("Invalid position");
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
current = start;
|
||||||
|
int index = 1;
|
||||||
|
while (current != null) {
|
||||||
|
if (index == position) {
|
||||||
|
int value = current.data;
|
||||||
|
if (current.prev != null) current.prev.next = current.next;
|
||||||
|
else start = current.next;
|
||||||
|
if (current.next != null) current.next.prev = current.prev;
|
||||||
|
else last = current.prev;
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
current = current.next;
|
||||||
|
index++;
|
||||||
|
}
|
||||||
|
out.println("Position out of range");
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The original main(), with the reader passed in. */
|
||||||
|
public void menu(BufferedReader reader) throws IOException {
|
||||||
|
DoublyLinkedList dll = new DoublyLinkedList();
|
||||||
|
int choice;
|
||||||
|
|
||||||
|
do {
|
||||||
|
out.println();
|
||||||
|
out.println("--- Doubly Linked List Menu ---");
|
||||||
|
out.println("1. Insert");
|
||||||
|
out.println("2. Remove");
|
||||||
|
out.println("3. Display list");
|
||||||
|
out.println("4. Search");
|
||||||
|
out.println("5. Exit");
|
||||||
|
out.print("Select option: ");
|
||||||
|
choice = Integer.parseInt(reader.readLine());
|
||||||
|
|
||||||
|
switch (choice) {
|
||||||
|
case 1:
|
||||||
|
out.println("1. Insert at first");
|
||||||
|
out.println("2. Insert at last");
|
||||||
|
out.println("3. Insert after position");
|
||||||
|
out.println("4. Insert before position");
|
||||||
|
out.print("Select: ");
|
||||||
|
int insertChoice = Integer.parseInt(reader.readLine());
|
||||||
|
out.print("Enter element: ");
|
||||||
|
int insertValue = Integer.parseInt(reader.readLine());
|
||||||
|
if (insertChoice == 1) {
|
||||||
|
dll.insertAtFirst(insertValue);
|
||||||
|
} else if (insertChoice == 2) {
|
||||||
|
dll.insertAtLast(insertValue);
|
||||||
|
} else if (insertChoice == 3) {
|
||||||
|
out.print("Enter position: ");
|
||||||
|
int pos = Integer.parseInt(reader.readLine());
|
||||||
|
dll.insertAfter(insertValue, pos);
|
||||||
|
} else if (insertChoice == 4) {
|
||||||
|
out.print("Enter position: ");
|
||||||
|
int pos = Integer.parseInt(reader.readLine());
|
||||||
|
dll.insertBefore(insertValue, pos);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case 2:
|
||||||
|
out.println("1. Delete first");
|
||||||
|
out.println("2. Delete last");
|
||||||
|
out.println("3. Delete at position");
|
||||||
|
out.print("Select: ");
|
||||||
|
int deleteChoice = Integer.parseInt(reader.readLine());
|
||||||
|
if (deleteChoice == 1) {
|
||||||
|
out.println("Deleted: " + dll.deleteFirst());
|
||||||
|
} else if (deleteChoice == 2) {
|
||||||
|
out.println("Deleted: " + dll.deleteLast());
|
||||||
|
} else if (deleteChoice == 3) {
|
||||||
|
out.print("Enter position: ");
|
||||||
|
int pos = Integer.parseInt(reader.readLine());
|
||||||
|
out.println("Deleted: " + dll.deleteAt(pos));
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case 3:
|
||||||
|
out.println("1. Forward display");
|
||||||
|
out.println("2. Reverse display");
|
||||||
|
out.print("Select: ");
|
||||||
|
int displayChoice = Integer.parseInt(reader.readLine());
|
||||||
|
if (displayChoice == 1) dll.displayForward();
|
||||||
|
else dll.displayReverse();
|
||||||
|
break;
|
||||||
|
case 4:
|
||||||
|
out.print("Enter element to search: ");
|
||||||
|
int searchValue = Integer.parseInt(reader.readLine());
|
||||||
|
int position = dll.search(searchValue);
|
||||||
|
out.println(position != -1
|
||||||
|
? "Element found at position: " + position
|
||||||
|
: "Element not found");
|
||||||
|
break;
|
||||||
|
case 5:
|
||||||
|
out.println("Exiting...");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
} while (choice != 5);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) throws IOException {
|
||||||
|
new LegacyDoublyDemo(System.out).menu(new BufferedReader(new InputStreamReader(System.in)));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,248 @@
|
|||||||
|
package com.ankurm.interviewlab.linkedlist;
|
||||||
|
|
||||||
|
import java.io.BufferedReader;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStreamReader;
|
||||||
|
import java.io.PrintStream;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The program from the 2015 article "Implementing Singly Linked List in Java", kept as it was so the new article can run it and
|
||||||
|
* measure it. The list logic is unchanged. Only two things moved: the classes became inner classes, and
|
||||||
|
* output goes through a PrintStream (instead of System.out) so a test can capture the session.
|
||||||
|
*/
|
||||||
|
public class LegacySinglyDemo {
|
||||||
|
private final PrintStream out;
|
||||||
|
|
||||||
|
public LegacySinglyDemo(PrintStream out) {
|
||||||
|
this.out = out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A single node in the singly linked list
|
||||||
|
class SLLNode {
|
||||||
|
int data;
|
||||||
|
SLLNode next; // Pointer to the next node; null if this is the last node
|
||||||
|
|
||||||
|
public SLLNode(int value) {
|
||||||
|
data = value;
|
||||||
|
next = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Singly Linked List with insert, remove, search, and display operations
|
||||||
|
class SinglyLinkedList {
|
||||||
|
SLLNode start = null; // Head node; null if the list is empty
|
||||||
|
|
||||||
|
public boolean isEmpty() {
|
||||||
|
return start == null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Inserts a new node at the beginning of the list
|
||||||
|
public void insertFirst(int value) {
|
||||||
|
SLLNode newNode = new SLLNode(value);
|
||||||
|
if (isEmpty()) {
|
||||||
|
start = newNode;
|
||||||
|
} else {
|
||||||
|
newNode.next = start; // New node points to old head
|
||||||
|
start = newNode; // Update head to new node
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Inserts a new node at the end of the list
|
||||||
|
public void insertLast(int value) {
|
||||||
|
SLLNode newNode = new SLLNode(value);
|
||||||
|
if (isEmpty()) {
|
||||||
|
start = newNode;
|
||||||
|
} else {
|
||||||
|
SLLNode current = start;
|
||||||
|
while (current.next != null) {
|
||||||
|
current = current.next; // Traverse to the last node
|
||||||
|
}
|
||||||
|
current.next = newNode;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Inserts a new node at the given 1-based position
|
||||||
|
public void insertAt(int value, int position) {
|
||||||
|
if (isEmpty() || position <= 1) {
|
||||||
|
insertFirst(value);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
SLLNode current = start;
|
||||||
|
int index = 1;
|
||||||
|
while (current != null) {
|
||||||
|
if (index == position - 1) {
|
||||||
|
SLLNode newNode = new SLLNode(value);
|
||||||
|
newNode.next = current.next;
|
||||||
|
current.next = newNode;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
current = current.next;
|
||||||
|
index++;
|
||||||
|
}
|
||||||
|
out.println("Position out of range - inserting at end");
|
||||||
|
insertLast(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Removes and returns the first element
|
||||||
|
public int removeFirst() {
|
||||||
|
if (isEmpty()) {
|
||||||
|
out.println("List is empty - nothing to remove");
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
int value = start.data;
|
||||||
|
start = start.next;
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Removes and returns the last element
|
||||||
|
public int removeLast() {
|
||||||
|
if (isEmpty()) {
|
||||||
|
out.println("List is empty - nothing to remove");
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
if (start.next == null) {
|
||||||
|
int value = start.data;
|
||||||
|
start = null;
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
SLLNode current = start;
|
||||||
|
while (current.next.next != null) {
|
||||||
|
current = current.next; // Stop at second-to-last node
|
||||||
|
}
|
||||||
|
int value = current.next.data;
|
||||||
|
current.next = null;
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Removes and returns the element at the given 1-based position
|
||||||
|
public int removeAt(int position) {
|
||||||
|
if (isEmpty()) {
|
||||||
|
out.println("List is empty - nothing to remove");
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
if (position <= 1) return removeFirst();
|
||||||
|
|
||||||
|
SLLNode current = start;
|
||||||
|
int index = 0;
|
||||||
|
while (current != null) {
|
||||||
|
if (index == position - 2) {
|
||||||
|
if (current.next == null) {
|
||||||
|
out.println("Position out of range");
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
int value = current.next.data;
|
||||||
|
current.next = current.next.next;
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
current = current.next;
|
||||||
|
index++;
|
||||||
|
}
|
||||||
|
out.println("Position out of range");
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Searches for a value and returns its 1-based position, or -1 if not found
|
||||||
|
public int search(int value) {
|
||||||
|
if (isEmpty()) {
|
||||||
|
out.println("List is empty");
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
SLLNode current = start;
|
||||||
|
int position = 1;
|
||||||
|
while (current != null) {
|
||||||
|
if (current.data == value) return position;
|
||||||
|
current = current.next;
|
||||||
|
position++;
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Displays all elements from head to tail
|
||||||
|
public void display() {
|
||||||
|
if (isEmpty()) {
|
||||||
|
out.println("List is empty");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
SLLNode current = start;
|
||||||
|
out.print("List: ");
|
||||||
|
while (current != null) {
|
||||||
|
out.print(current.data + " ");
|
||||||
|
current = current.next;
|
||||||
|
}
|
||||||
|
out.println();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The original main(), with the reader passed in. */
|
||||||
|
public void menu(BufferedReader reader) throws IOException {
|
||||||
|
SinglyLinkedList list = new SinglyLinkedList();
|
||||||
|
int choice;
|
||||||
|
|
||||||
|
do {
|
||||||
|
out.println();
|
||||||
|
out.println("--- Singly Linked List Menu ---");
|
||||||
|
out.println("1. Insert");
|
||||||
|
out.println("2. Remove");
|
||||||
|
out.println("3. Search");
|
||||||
|
out.println("4. Display");
|
||||||
|
out.println("5. Exit");
|
||||||
|
out.print("Enter choice: ");
|
||||||
|
choice = Integer.parseInt(reader.readLine());
|
||||||
|
|
||||||
|
switch (choice) {
|
||||||
|
case 1:
|
||||||
|
out.println("1. Insert at position");
|
||||||
|
out.println("2. Insert at first");
|
||||||
|
out.println("3. Insert at last");
|
||||||
|
out.print("Enter choice: ");
|
||||||
|
int insertChoice = Integer.parseInt(reader.readLine());
|
||||||
|
out.print("Enter element: ");
|
||||||
|
int insertValue = Integer.parseInt(reader.readLine());
|
||||||
|
if (insertChoice == 1) {
|
||||||
|
out.print("Enter position: ");
|
||||||
|
int pos = Integer.parseInt(reader.readLine());
|
||||||
|
list.insertAt(insertValue, pos);
|
||||||
|
} else if (insertChoice == 2) {
|
||||||
|
list.insertFirst(insertValue);
|
||||||
|
} else if (insertChoice == 3) {
|
||||||
|
list.insertLast(insertValue);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case 2:
|
||||||
|
out.println("1. Remove first element");
|
||||||
|
out.println("2. Remove last element");
|
||||||
|
out.println("3. Remove element at position");
|
||||||
|
out.print("Enter choice: ");
|
||||||
|
int removeChoice = Integer.parseInt(reader.readLine());
|
||||||
|
if (removeChoice == 1) {
|
||||||
|
out.println("Removed: " + list.removeFirst());
|
||||||
|
} else if (removeChoice == 2) {
|
||||||
|
out.println("Removed: " + list.removeLast());
|
||||||
|
} else if (removeChoice == 3) {
|
||||||
|
out.print("Enter position: ");
|
||||||
|
int pos = Integer.parseInt(reader.readLine());
|
||||||
|
out.println("Removed: " + list.removeAt(pos));
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case 3:
|
||||||
|
out.print("Enter element to search: ");
|
||||||
|
int searchValue = Integer.parseInt(reader.readLine());
|
||||||
|
int position = list.search(searchValue);
|
||||||
|
out.println(position != -1
|
||||||
|
? "Element found at position: " + position
|
||||||
|
: "Element not found");
|
||||||
|
break;
|
||||||
|
case 4:
|
||||||
|
list.display();
|
||||||
|
break;
|
||||||
|
case 5:
|
||||||
|
out.println("Exiting...");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
} while (choice != 5);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) throws IOException {
|
||||||
|
new LegacySinglyDemo(System.out).menu(new BufferedReader(new InputStreamReader(System.in)));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,173 @@
|
|||||||
|
package com.ankurm.interviewlab.linkedlist;
|
||||||
|
|
||||||
|
/** Classic linked-list interview problems on ListNode chains. Each method says what it costs in time and extra space. */
|
||||||
|
public final class LinkedListProblems {
|
||||||
|
private LinkedListProblems() {
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Reverse in place with three pointers. O(n) time, O(1) space. */
|
||||||
|
public static ListNode reverseIterative(ListNode head) {
|
||||||
|
ListNode prev = null;
|
||||||
|
ListNode cur = head;
|
||||||
|
while (cur != null) {
|
||||||
|
ListNode next = cur.next; // remember the rest before we cut the link
|
||||||
|
cur.next = prev; // turn this node around
|
||||||
|
prev = cur;
|
||||||
|
cur = next;
|
||||||
|
}
|
||||||
|
return prev;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Reverse by trusting the recursion to reverse the tail. O(n) time, but O(n) stack depth. */
|
||||||
|
public static ListNode reverseRecursive(ListNode head) {
|
||||||
|
if (head == null || head.next == null) {
|
||||||
|
return head;
|
||||||
|
}
|
||||||
|
ListNode newHead = reverseRecursive(head.next);
|
||||||
|
head.next.next = head;
|
||||||
|
head.next = null;
|
||||||
|
return newHead;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The middle node; for an even length, the second of the two middles. O(n) time, O(1) space. */
|
||||||
|
public static ListNode middle(ListNode head) {
|
||||||
|
ListNode slow = head;
|
||||||
|
ListNode fast = head;
|
||||||
|
while (fast != null && fast.next != null) {
|
||||||
|
slow = slow.next;
|
||||||
|
fast = fast.next.next;
|
||||||
|
}
|
||||||
|
return slow;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Floyd's tortoise and hare. O(n) time, O(1) space. */
|
||||||
|
public static boolean hasCycle(ListNode head) {
|
||||||
|
ListNode slow = head;
|
||||||
|
ListNode fast = head;
|
||||||
|
while (fast != null && fast.next != null) {
|
||||||
|
slow = slow.next;
|
||||||
|
fast = fast.next.next;
|
||||||
|
if (slow == fast) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The node where the cycle begins, or null when there is no cycle. */
|
||||||
|
public static ListNode cycleStart(ListNode head) {
|
||||||
|
ListNode slow = head;
|
||||||
|
ListNode fast = head;
|
||||||
|
while (fast != null && fast.next != null) {
|
||||||
|
slow = slow.next;
|
||||||
|
fast = fast.next.next;
|
||||||
|
if (slow == fast) {
|
||||||
|
ListNode probe = head;
|
||||||
|
while (probe != slow) {
|
||||||
|
probe = probe.next;
|
||||||
|
slow = slow.next;
|
||||||
|
}
|
||||||
|
return probe;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Number of nodes in the cycle, or 0 when there is none. */
|
||||||
|
public static int cycleLength(ListNode head) {
|
||||||
|
ListNode slow = head;
|
||||||
|
ListNode fast = head;
|
||||||
|
while (fast != null && fast.next != null) {
|
||||||
|
slow = slow.next;
|
||||||
|
fast = fast.next.next;
|
||||||
|
if (slow == fast) {
|
||||||
|
int length = 1;
|
||||||
|
for (ListNode cur = slow.next; cur != slow; cur = cur.next) {
|
||||||
|
length++;
|
||||||
|
}
|
||||||
|
return length;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Merge two sorted lists by relinking their nodes; no new nodes. O(n + m) time, O(1) space. */
|
||||||
|
public static ListNode mergeSorted(ListNode a, ListNode b) {
|
||||||
|
ListNode dummy = new ListNode(0); // a fake head so the first node is not a special case
|
||||||
|
ListNode tail = dummy;
|
||||||
|
while (a != null && b != null) {
|
||||||
|
if (a.val <= b.val) {
|
||||||
|
tail.next = a;
|
||||||
|
a = a.next;
|
||||||
|
} else {
|
||||||
|
tail.next = b;
|
||||||
|
b = b.next;
|
||||||
|
}
|
||||||
|
tail = tail.next;
|
||||||
|
}
|
||||||
|
tail.next = (a != null) ? a : b; // one list is used up; the other is already sorted, so attach it whole
|
||||||
|
return dummy.next;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Remove the n-th node from the end (n = 1 is the last node) in one pass with two pointers n apart. */
|
||||||
|
public static ListNode removeNthFromEnd(ListNode head, int n) {
|
||||||
|
if (n < 1) {
|
||||||
|
throw new IllegalArgumentException("n must be at least 1");
|
||||||
|
}
|
||||||
|
ListNode dummy = new ListNode(0, head);
|
||||||
|
ListNode lead = dummy;
|
||||||
|
ListNode lag = dummy;
|
||||||
|
for (int i = 0; i < n; i++) {
|
||||||
|
lead = lead.next;
|
||||||
|
if (lead == null) {
|
||||||
|
throw new IllegalArgumentException("n = " + n + " is longer than the list");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
while (lead.next != null) {
|
||||||
|
lead = lead.next;
|
||||||
|
lag = lag.next;
|
||||||
|
}
|
||||||
|
lag.next = lag.next.next;
|
||||||
|
return dummy.next;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Palindrome check in O(1) extra space: reverse the second half, compare, then put it back. */
|
||||||
|
public static boolean isPalindrome(ListNode head) {
|
||||||
|
ListNode mid = middle(head);
|
||||||
|
ListNode right = reverseIterative(mid);
|
||||||
|
ListNode left = head;
|
||||||
|
boolean same = true;
|
||||||
|
for (ListNode r = right; r != null; r = r.next, left = left.next) {
|
||||||
|
if (r.val != left.val) {
|
||||||
|
same = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
reverseIterative(right); // restore the list for the caller
|
||||||
|
return same;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Drop repeated values from a sorted list, keeping one of each. */
|
||||||
|
public static ListNode removeDuplicatesSorted(ListNode head) {
|
||||||
|
ListNode cur = head;
|
||||||
|
while (cur != null) {
|
||||||
|
if (cur.next != null && cur.next.val == cur.val) {
|
||||||
|
cur.next = cur.next.next;
|
||||||
|
} else {
|
||||||
|
cur = cur.next;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return head;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The node where two acyclic lists join (same node object, not just equal values), or null. */
|
||||||
|
public static ListNode intersection(ListNode headA, ListNode headB) {
|
||||||
|
ListNode a = headA;
|
||||||
|
ListNode b = headB;
|
||||||
|
while (a != b) {
|
||||||
|
a = (a == null) ? headB : a.next; // after finishing one list, continue along the other
|
||||||
|
b = (b == null) ? headA : b.next;
|
||||||
|
}
|
||||||
|
return a;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
package com.ankurm.interviewlab.linkedlist;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One node of a singly linked list: a value and a link to the next node.
|
||||||
|
* The last node's {@code next} is {@code null}, and a {@code null} head is the empty list.
|
||||||
|
*/
|
||||||
|
public final class ListNode {
|
||||||
|
public int val;
|
||||||
|
public ListNode next;
|
||||||
|
|
||||||
|
public ListNode(int val) {
|
||||||
|
this.val = val;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ListNode(int val, ListNode next) {
|
||||||
|
this.val = val;
|
||||||
|
this.next = next;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Builds a chain from the values; of(1, 2, 3) is 1 -> 2 -> 3. No values gives null, the empty list. */
|
||||||
|
public static ListNode of(int... values) {
|
||||||
|
ListNode dummy = new ListNode(0);
|
||||||
|
ListNode tail = dummy;
|
||||||
|
for (int v : values) {
|
||||||
|
tail.next = new ListNode(v);
|
||||||
|
tail = tail.next;
|
||||||
|
}
|
||||||
|
return dummy.next;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Builds a chain whose last node links back to the node at index {@code cycleAt}
|
||||||
|
* (so the list has a cycle), or a plain chain when {@code cycleAt} is -1.
|
||||||
|
*/
|
||||||
|
public static ListNode withCycle(int[] values, int cycleAt) {
|
||||||
|
ListNode head = of(values);
|
||||||
|
if (cycleAt >= 0) {
|
||||||
|
ListNode target = head;
|
||||||
|
for (int i = 0; i < cycleAt; i++) {
|
||||||
|
target = target.next;
|
||||||
|
}
|
||||||
|
ListNode last = head;
|
||||||
|
while (last.next != null) {
|
||||||
|
last = last.next;
|
||||||
|
}
|
||||||
|
last.next = target;
|
||||||
|
}
|
||||||
|
return head;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Number of nodes in an acyclic list. Never call this on a list that has a cycle. */
|
||||||
|
public static int length(ListNode head) {
|
||||||
|
int n = 0;
|
||||||
|
for (ListNode cur = head; cur != null; cur = cur.next) {
|
||||||
|
n++;
|
||||||
|
}
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The values of an acyclic list, in order. */
|
||||||
|
public static int[] toArray(ListNode head) {
|
||||||
|
int[] out = new int[length(head)];
|
||||||
|
int i = 0;
|
||||||
|
for (ListNode cur = head; cur != null; cur = cur.next) {
|
||||||
|
out[i++] = cur.val;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "1 -> 2 -> 3 -> null". Stops after 12 nodes with "..." so printing a cyclic list cannot hang. */
|
||||||
|
public static String show(ListNode head) {
|
||||||
|
return show(head, 12);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String show(ListNode head, int limit) {
|
||||||
|
StringBuilder sb = new StringBuilder();
|
||||||
|
int count = 0;
|
||||||
|
for (ListNode cur = head; cur != null; cur = cur.next) {
|
||||||
|
if (count == limit) {
|
||||||
|
sb.append("...");
|
||||||
|
return sb.toString();
|
||||||
|
}
|
||||||
|
sb.append(cur.val).append(" -> ");
|
||||||
|
count++;
|
||||||
|
}
|
||||||
|
return sb.append("null").toString();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
package com.ankurm.interviewlab.linkedlist;
|
||||||
|
|
||||||
|
/** Plausible-looking wrong versions, kept so the article can run them and show what each mistake actually does. */
|
||||||
|
public final class Pitfalls {
|
||||||
|
private Pitfalls() {
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Overwrites cur.next and then reads it as the "next" node: the rest of the list is lost after one pass. */
|
||||||
|
public static ListNode reverseThatLosesTheRest(ListNode head) {
|
||||||
|
ListNode prev = null;
|
||||||
|
ListNode cur = head;
|
||||||
|
while (cur != null) {
|
||||||
|
cur.next = prev;
|
||||||
|
prev = cur;
|
||||||
|
cur = cur.next; // BUG: cur.next is now prev's old value, not the node after cur
|
||||||
|
}
|
||||||
|
return prev;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Looks one node ahead, so a match on the head itself is never examined. */
|
||||||
|
public static ListNode removeValueIgnoringHead(ListNode head, int value) {
|
||||||
|
ListNode cur = head;
|
||||||
|
while (cur != null && cur.next != null) {
|
||||||
|
if (cur.next.val == value) {
|
||||||
|
cur.next = cur.next.next;
|
||||||
|
} else {
|
||||||
|
cur = cur.next;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return head;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The fix: a dummy node in front of the head makes "remove the head" the same as "remove any other node". */
|
||||||
|
public static ListNode removeValue(ListNode head, int value) {
|
||||||
|
ListNode dummy = new ListNode(0, head);
|
||||||
|
ListNode cur = dummy;
|
||||||
|
while (cur.next != null) {
|
||||||
|
if (cur.next.val == value) {
|
||||||
|
cur.next = cur.next.next;
|
||||||
|
} else {
|
||||||
|
cur = cur.next;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return dummy.next;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Checks only fast, not fast.next, so fast.next.next throws on any list whose length is odd. */
|
||||||
|
public static boolean hasCycleThatThrows(ListNode head) {
|
||||||
|
ListNode slow = head;
|
||||||
|
ListNode fast = head;
|
||||||
|
while (fast != null) { // BUG: also needs fast.next != null
|
||||||
|
slow = slow.next;
|
||||||
|
fast = fast.next.next;
|
||||||
|
if (slow == fast) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Stops as soon as one list runs out and forgets to attach what is left of the other. */
|
||||||
|
public static ListNode mergeThatDropsTheTail(ListNode a, ListNode b) {
|
||||||
|
ListNode dummy = new ListNode(0);
|
||||||
|
ListNode tail = dummy;
|
||||||
|
while (a != null && b != null) {
|
||||||
|
if (a.val <= b.val) {
|
||||||
|
tail.next = a;
|
||||||
|
a = a.next;
|
||||||
|
} else {
|
||||||
|
tail.next = b;
|
||||||
|
b = b.next;
|
||||||
|
}
|
||||||
|
tail = tail.next;
|
||||||
|
}
|
||||||
|
return dummy.next; // BUG: missing tail.next = (a != null) ? a : b;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Compares nodes by value instead of by identity, so "same values" is mistaken for "same node". */
|
||||||
|
public static boolean sameNodeByValue(ListNode a, ListNode b) {
|
||||||
|
return a != null && b != null && a.val == b.val;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,183 @@
|
|||||||
|
package com.ankurm.interviewlab.linkedlist;
|
||||||
|
|
||||||
|
import java.util.NoSuchElementException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A singly linked list of ints with zero-based positions, like java.util.List.
|
||||||
|
* It counts every {@code next} link it follows ("hops") so the cost of each operation can be measured
|
||||||
|
* rather than recited. {@code keepTail = false} shows what the 2015 version paid for not remembering the last node.
|
||||||
|
*/
|
||||||
|
public final class SinglyLinkedList {
|
||||||
|
private final boolean keepTail;
|
||||||
|
private ListNode head;
|
||||||
|
private ListNode tail;
|
||||||
|
private int size;
|
||||||
|
private long hops;
|
||||||
|
|
||||||
|
public SinglyLinkedList() {
|
||||||
|
this(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
public SinglyLinkedList(boolean keepTail) {
|
||||||
|
this.keepTail = keepTail;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int size() {
|
||||||
|
return size;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isEmpty() {
|
||||||
|
return size == 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ListNode head() {
|
||||||
|
return head;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** How many next links have been followed since construction or the last resetHops(). */
|
||||||
|
public long hops() {
|
||||||
|
return hops;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void resetHops() {
|
||||||
|
hops = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** O(1): the new node points at the old head, then becomes the head. */
|
||||||
|
public void addFirst(int value) {
|
||||||
|
head = new ListNode(value, head);
|
||||||
|
if (tail == null) {
|
||||||
|
tail = head;
|
||||||
|
}
|
||||||
|
size++;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** O(1) with a tail pointer; O(n) without one, because the last node has to be found by walking. */
|
||||||
|
public void addLast(int value) {
|
||||||
|
ListNode node = new ListNode(value);
|
||||||
|
if (head == null) {
|
||||||
|
head = node;
|
||||||
|
} else if (keepTail) {
|
||||||
|
tail.next = node;
|
||||||
|
} else {
|
||||||
|
ListNode cur = head;
|
||||||
|
while (cur.next != null) {
|
||||||
|
cur = cur.next;
|
||||||
|
hops++;
|
||||||
|
}
|
||||||
|
cur.next = node;
|
||||||
|
}
|
||||||
|
tail = node;
|
||||||
|
size++;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Inserts so that the new value ends up at {@code index}; index == size() appends. */
|
||||||
|
public void add(int index, int value) {
|
||||||
|
if (index < 0 || index > size) {
|
||||||
|
throw new IndexOutOfBoundsException("index " + index + ", size " + size);
|
||||||
|
}
|
||||||
|
if (index == 0) {
|
||||||
|
addFirst(value);
|
||||||
|
} else if (index == size) {
|
||||||
|
addLast(value);
|
||||||
|
} else {
|
||||||
|
ListNode before = nodeAt(index - 1);
|
||||||
|
before.next = new ListNode(value, before.next);
|
||||||
|
size++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public int get(int index) {
|
||||||
|
checkElementIndex(index);
|
||||||
|
return nodeAt(index).val;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Position of the first node holding {@code value}, or -1. */
|
||||||
|
public int indexOf(int value) {
|
||||||
|
int index = 0;
|
||||||
|
for (ListNode cur = head; cur != null; cur = cur.next) {
|
||||||
|
if (cur.val == value) {
|
||||||
|
return index;
|
||||||
|
}
|
||||||
|
index++;
|
||||||
|
hops++;
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** O(1). Throws on an empty list instead of returning a fake 0 that could be a real value. */
|
||||||
|
public int removeFirst() {
|
||||||
|
if (head == null) {
|
||||||
|
throw new NoSuchElementException("list is empty");
|
||||||
|
}
|
||||||
|
int value = head.val;
|
||||||
|
head = head.next;
|
||||||
|
if (head == null) {
|
||||||
|
tail = null;
|
||||||
|
}
|
||||||
|
size--;
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** O(n) even with a tail pointer: to drop the last node you need the one before it, and nothing points backwards. */
|
||||||
|
public int removeLast() {
|
||||||
|
if (head == null) {
|
||||||
|
throw new NoSuchElementException("list is empty");
|
||||||
|
}
|
||||||
|
if (head.next == null) {
|
||||||
|
return removeFirst();
|
||||||
|
}
|
||||||
|
ListNode beforeLast = nodeAt(size - 2);
|
||||||
|
int value = beforeLast.next.val;
|
||||||
|
beforeLast.next = null;
|
||||||
|
tail = beforeLast;
|
||||||
|
size--;
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int remove(int index) {
|
||||||
|
checkElementIndex(index);
|
||||||
|
if (index == 0) {
|
||||||
|
return removeFirst();
|
||||||
|
}
|
||||||
|
ListNode before = nodeAt(index - 1);
|
||||||
|
int value = before.next.val;
|
||||||
|
before.next = before.next.next;
|
||||||
|
if (before.next == null) {
|
||||||
|
tail = before;
|
||||||
|
}
|
||||||
|
size--;
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int[] toArray() {
|
||||||
|
return ListNode.toArray(head);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
StringBuilder sb = new StringBuilder("[");
|
||||||
|
for (ListNode cur = head; cur != null; cur = cur.next) {
|
||||||
|
sb.append(cur.val);
|
||||||
|
if (cur.next != null) {
|
||||||
|
sb.append(", ");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return sb.append("]").toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private ListNode nodeAt(int index) {
|
||||||
|
ListNode cur = head;
|
||||||
|
for (int i = 0; i < index; i++) {
|
||||||
|
cur = cur.next;
|
||||||
|
hops++;
|
||||||
|
}
|
||||||
|
return cur;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void checkElementIndex(int index) {
|
||||||
|
if (index < 0 || index >= size) {
|
||||||
|
throw new IndexOutOfBoundsException("index " + index + ", size " + size);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
package com.ankurm.interviewlab.linkedlist;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
import com.ankurm.interviewlab.linkedlist.support.Transcript;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
class DoublyListTest {
|
||||||
|
@Test
|
||||||
|
void bothDirectionsAndConstantTimeUnlinking() {
|
||||||
|
Transcript t = Transcript.start("07-doubly-list.txt", "DoublyLinkedList: two links per node, and what that buys");
|
||||||
|
DoublyLinkedList list = new DoublyLinkedList();
|
||||||
|
list.addLast(20);
|
||||||
|
list.addFirst(40);
|
||||||
|
list.addLast(60);
|
||||||
|
t.line("addLast(20), addFirst(40), addLast(60)");
|
||||||
|
t.line(" forward (next links): " + DoublyLinkedList.show(list.toArray()));
|
||||||
|
t.line(" backward (prev links): " + DoublyLinkedList.show(list.toArrayReversed()));
|
||||||
|
assertArrayEquals(new int[] {40, 20, 60}, list.toArray());
|
||||||
|
assertArrayEquals(new int[] {60, 20, 40}, list.toArrayReversed());
|
||||||
|
t.blank();
|
||||||
|
|
||||||
|
DoublyLinkedList.Node twenty = list.first().next();
|
||||||
|
list.addAfter(twenty, 45);
|
||||||
|
list.addBefore(twenty, 65);
|
||||||
|
t.line("addAfter(node 20, 45) and addBefore(node 20, 65)");
|
||||||
|
t.line(" forward: " + DoublyLinkedList.show(list.toArray()));
|
||||||
|
t.line(" backward: " + DoublyLinkedList.show(list.toArrayReversed()));
|
||||||
|
assertArrayEquals(new int[] {40, 65, 20, 45, 60}, list.toArray());
|
||||||
|
assertArrayEquals(new int[] {60, 45, 20, 65, 40}, list.toArrayReversed());
|
||||||
|
t.blank();
|
||||||
|
|
||||||
|
list.addAfter(list.last(), 99);
|
||||||
|
t.line("addAfter(the last node, 99): the tail has to move, and it does");
|
||||||
|
t.line(" forward: " + DoublyLinkedList.show(list.toArray()));
|
||||||
|
t.line(" backward: " + DoublyLinkedList.show(list.toArrayReversed()));
|
||||||
|
assertArrayEquals(new int[] {40, 65, 20, 45, 60, 99}, list.toArray());
|
||||||
|
assertArrayEquals(new int[] {99, 60, 45, 20, 65, 40}, list.toArrayReversed());
|
||||||
|
assertEquals(99, list.last().val);
|
||||||
|
t.line(" last().val = " + list.last().val + ", removeLast() returned " + list.removeLast());
|
||||||
|
t.blank();
|
||||||
|
|
||||||
|
int n = 1000;
|
||||||
|
DoublyLinkedList big = new DoublyLinkedList();
|
||||||
|
SinglyLinkedList singly = new SinglyLinkedList();
|
||||||
|
for (int i = 0; i < n; i++) {
|
||||||
|
big.addLast(i);
|
||||||
|
singly.addLast(i);
|
||||||
|
}
|
||||||
|
t.line("Links followed to reach one element of a " + n + "-element list:");
|
||||||
|
t.line(String.format(" %-8s | %-18s | %s", "index", "doubly (nearer end)", "singly (from head)"));
|
||||||
|
for (int index : new int[] {0, 250, 499, 500, 750, 999}) {
|
||||||
|
big.resetHops();
|
||||||
|
singly.resetHops();
|
||||||
|
assertEquals(index, big.get(index));
|
||||||
|
assertEquals(index, singly.get(index));
|
||||||
|
long expected = (index < n / 2) ? index : n - 1 - index;
|
||||||
|
assertEquals(expected, big.hops());
|
||||||
|
assertEquals(index, singly.hops());
|
||||||
|
t.line(String.format(" %-8d | %-19d | %d", index, big.hops(), singly.hops()));
|
||||||
|
}
|
||||||
|
t.blank();
|
||||||
|
|
||||||
|
DoublyLinkedList.Node held = big.nodeAt(700);
|
||||||
|
big.resetHops();
|
||||||
|
big.remove(held);
|
||||||
|
long doublyHops = big.hops();
|
||||||
|
singly.resetHops();
|
||||||
|
singly.remove(700);
|
||||||
|
t.line("Unlinking the element at index 700 when you already hold the node:");
|
||||||
|
t.line(" doubly: " + doublyHops + " links followed (the node knows its neighbours)");
|
||||||
|
t.line(" singly: " + singly.hops() + " links followed (it must walk to the node before it)");
|
||||||
|
assertEquals(0, doublyHops);
|
||||||
|
assertEquals(699, singly.hops());
|
||||||
|
t.flush();
|
||||||
|
}
|
||||||
|
}
|
||||||
+73
@@ -0,0 +1,73 @@
|
|||||||
|
package com.ankurm.interviewlab.linkedlist;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
import com.ankurm.interviewlab.linkedlist.support.Transcript;
|
||||||
|
import java.io.BufferedReader;
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.io.PrintStream;
|
||||||
|
import java.io.StringReader;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
/** Runs the two 2015 menu programs with the same keystrokes as the 2015 articles and compares character for character. */
|
||||||
|
class InteractiveSessionsTest {
|
||||||
|
private static final String SINGLY_KEYS = "1 2 10 1 3 50 1 1 20 2 1 3 90 4 3 50 3 1 2 1 2 2 4 1 3 80 4 2 3 2 4 5";
|
||||||
|
private static final String DOUBLY_KEYS = "1 1 20 1 1 40 1 2 60 1 3 45 2 1 4 65 2 3 1 3 2 2 1 2 2 3 1 4 20 2 3 2 3 1 5";
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void singlySessionMatchesThe2015Article() throws IOException {
|
||||||
|
String session = run(SINGLY_KEYS, true);
|
||||||
|
String expected = resource("original-2015-singly-session.txt");
|
||||||
|
assertEquals(expected.strip(), session.strip());
|
||||||
|
Transcript t = Transcript.start("13-singly-session.txt", "The 2015 singly linked list menu program, same keystrokes as the original article");
|
||||||
|
t.line("keystrokes: " + SINGLY_KEYS.replaceAll(" +", " "));
|
||||||
|
t.line("output identical to the 2015 article's sample output: " + expected.strip().equals(session.strip())).blank();
|
||||||
|
for (String line : session.strip().split("\n")) {
|
||||||
|
t.line(line.stripTrailing());
|
||||||
|
}
|
||||||
|
t.flush();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void doublySessionMatchesThe2015Article() throws IOException {
|
||||||
|
String session = run(DOUBLY_KEYS, false);
|
||||||
|
String expected = resource("original-2015-doubly-session.txt");
|
||||||
|
assertEquals(expected.strip(), session.strip());
|
||||||
|
Transcript t = Transcript.start("14-doubly-session.txt", "The 2015 doubly linked list menu program, same keystrokes as the original article");
|
||||||
|
t.line("keystrokes: " + DOUBLY_KEYS.replaceAll(" +", " "));
|
||||||
|
t.line("output identical to the 2015 article's sample output: " + expected.strip().equals(session.strip())).blank();
|
||||||
|
for (String line : session.strip().split("\n")) {
|
||||||
|
t.line(line.stripTrailing());
|
||||||
|
}
|
||||||
|
t.flush();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String run(String keys, boolean singly) throws IOException {
|
||||||
|
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
|
||||||
|
PrintStream out = new PrintStream(buffer, true, StandardCharsets.UTF_8);
|
||||||
|
// A terminal shows what you type. The 2015 sample output was pasted from one, so echo every line the program reads.
|
||||||
|
BufferedReader in = new BufferedReader(new StringReader(String.join("\n", keys.trim().split("\\s+")) + "\n")) {
|
||||||
|
@Override
|
||||||
|
public String readLine() throws IOException {
|
||||||
|
String line = super.readLine();
|
||||||
|
out.println(line);
|
||||||
|
return line;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if (singly) {
|
||||||
|
new LegacySinglyDemo(out).menu(in);
|
||||||
|
} else {
|
||||||
|
new LegacyDoublyDemo(out).menu(in);
|
||||||
|
}
|
||||||
|
return buffer.toString(StandardCharsets.UTF_8).replace("\r\n", "\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String resource(String name) throws IOException {
|
||||||
|
try (InputStream in = InteractiveSessionsTest.class.getResourceAsStream("/" + name)) {
|
||||||
|
return new String(in.readAllBytes(), StandardCharsets.UTF_8).replace("\r\n", "\n");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
package com.ankurm.interviewlab.linkedlist;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
import static org.junit.jupiter.api.Assumptions.assumeTrue;
|
||||||
|
|
||||||
|
import com.ankurm.interviewlab.linkedlist.support.Transcript;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.lang.reflect.Field;
|
||||||
|
import java.nio.file.FileSystems;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
/** Reads java.util.LinkedList from this JDK instead of trusting memory about it. */
|
||||||
|
class JdkLinkedListTest {
|
||||||
|
@Test
|
||||||
|
void javaUtilLinkedListIsADoublyLinkedList() throws Exception {
|
||||||
|
Transcript t = Transcript.start("15-jdk-linkedlist.txt", "java.util.LinkedList, read from this JDK");
|
||||||
|
t.line("JDK: " + Runtime.version()).blank();
|
||||||
|
Class<?> node = Class.forName("java.util.LinkedList$Node");
|
||||||
|
List<String> fields = new ArrayList<>();
|
||||||
|
for (Field f : node.getDeclaredFields()) {
|
||||||
|
fields.add(f.getType().getSimpleName() + " " + f.getName());
|
||||||
|
}
|
||||||
|
fields.sort(String::compareTo);
|
||||||
|
t.line("fields of java.util.LinkedList$Node (reflection): " + fields);
|
||||||
|
assertEquals(List.of("E item", "Node next", "Node prev").size(), fields.size());
|
||||||
|
assertTrue(fields.contains("Node next") && fields.contains("Node prev") && fields.contains("Object item"));
|
||||||
|
t.line("interfaces of java.util.LinkedList: " + Arrays.stream(java.util.LinkedList.class.getInterfaces()).map(Class::getSimpleName).toList()).blank();
|
||||||
|
|
||||||
|
Path zip = Path.of(System.getProperty("java.home"), "lib", "src.zip");
|
||||||
|
assumeTrue(Files.exists(zip), "this JDK has no lib/src.zip");
|
||||||
|
try (var fs = FileSystems.newFileSystem(zip)) {
|
||||||
|
List<String> src = Files.readAllLines(fs.getPath("java.base/java/util/LinkedList.java"));
|
||||||
|
int start = -1;
|
||||||
|
for (int i = 0; i < src.size(); i++) {
|
||||||
|
if (src.get(i).contains("Node<E> node(int index) {")) {
|
||||||
|
start = i;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertTrue(start >= 0, "node(int) not found");
|
||||||
|
t.line("java/util/LinkedList.java, node(int index), from line " + (start + 1) + ":");
|
||||||
|
boolean nearerEnd = false;
|
||||||
|
for (int i = start; i < src.size(); i++) {
|
||||||
|
String line = src.get(i);
|
||||||
|
t.line(String.format("%5d %s", i + 1, line));
|
||||||
|
nearerEnd |= line.contains("index < (size >> 1)");
|
||||||
|
if (line.equals(" }")) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertTrue(nearerEnd, "expected node(int) to pick the nearer end with index < (size >> 1)");
|
||||||
|
}
|
||||||
|
t.flush();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
package com.ankurm.interviewlab.linkedlist;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
|
||||||
|
import com.ankurm.interviewlab.linkedlist.support.Transcript;
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.io.PrintStream;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.NoSuchElementException;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
/** Runs the 2015 code as published and shows two real defects found while rewriting the article. */
|
||||||
|
class LegacyBugsTest {
|
||||||
|
@Test
|
||||||
|
void the2015DoublyListForgetsTheTail() {
|
||||||
|
Transcript t = Transcript.start("08-legacy-bugs.txt", "Two defects in the 2015 programs, reproduced");
|
||||||
|
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
|
||||||
|
PrintStream out = new PrintStream(buffer, true, StandardCharsets.UTF_8);
|
||||||
|
LegacyDoublyDemo demo = new LegacyDoublyDemo(out);
|
||||||
|
LegacyDoublyDemo.DoublyLinkedList old = demo.new DoublyLinkedList();
|
||||||
|
old.insertAtLast(1);
|
||||||
|
old.insertAtLast(2);
|
||||||
|
old.insertAtLast(3);
|
||||||
|
old.insertAfter(4, 3); // "insert 4 after position 3", and position 3 is the last node
|
||||||
|
t.line("2015 DoublyLinkedList: insertAtLast(1), insertAtLast(2), insertAtLast(3), then insertAfter(4, position 3)");
|
||||||
|
old.displayForward();
|
||||||
|
old.displayReverse();
|
||||||
|
for (String line : buffer.toString(StandardCharsets.UTF_8).split("\n")) {
|
||||||
|
t.line(" " + line.stripTrailing());
|
||||||
|
}
|
||||||
|
t.line(" last.data = " + old.last.data + " (the new node 4 is the real last node, but 'last' was never moved)");
|
||||||
|
assertEquals(3, old.last.data);
|
||||||
|
buffer.reset();
|
||||||
|
int returned = old.deleteLast();
|
||||||
|
old.displayForward();
|
||||||
|
t.line(" deleteLast() returned " + returned + "; forward now: " + buffer.toString(StandardCharsets.UTF_8).strip());
|
||||||
|
t.line(" it should have removed only 4 and returned 4; instead both 3 and 4 are gone and the caller saw only the 3.");
|
||||||
|
assertEquals(3, returned);
|
||||||
|
assertEquals("Forward: 1 2", buffer.toString(StandardCharsets.UTF_8).strip());
|
||||||
|
t.blank();
|
||||||
|
|
||||||
|
DoublyLinkedList fixed = new DoublyLinkedList();
|
||||||
|
fixed.addLast(1);
|
||||||
|
fixed.addLast(2);
|
||||||
|
DoublyLinkedList.Node three = fixed.addLast(3);
|
||||||
|
fixed.addAfter(three, 4);
|
||||||
|
t.line("the DoublyLinkedList in this module, same operations:");
|
||||||
|
t.line(" forward: " + DoublyLinkedList.show(fixed.toArray()));
|
||||||
|
t.line(" backward: " + DoublyLinkedList.show(fixed.toArrayReversed()));
|
||||||
|
assertEquals("[4, 3, 2, 1]", DoublyLinkedList.show(fixed.toArrayReversed()));
|
||||||
|
t.line(" removeLast() returned " + fixed.removeLast());
|
||||||
|
t.flush();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void the2015SinglyListReturnsZeroForNothing() {
|
||||||
|
Transcript t = Transcript.start("09-legacy-sentinel.txt", "removeFirst() on an empty list, 2015 version and this module");
|
||||||
|
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
|
||||||
|
PrintStream out = new PrintStream(buffer, true, StandardCharsets.UTF_8);
|
||||||
|
LegacySinglyDemo demo = new LegacySinglyDemo(out);
|
||||||
|
|
||||||
|
LegacySinglyDemo.SinglyLinkedList holdsZero = demo.new SinglyLinkedList();
|
||||||
|
holdsZero.insertFirst(0);
|
||||||
|
int fromRealZero = holdsZero.removeFirst();
|
||||||
|
LegacySinglyDemo.SinglyLinkedList empty = demo.new SinglyLinkedList();
|
||||||
|
int fromNothing = empty.removeFirst();
|
||||||
|
t.line("2015 list holding the value 0: removeFirst() returned " + fromRealZero);
|
||||||
|
t.line("2015 list that is empty: removeFirst() returned " + fromNothing + " (and printed: "
|
||||||
|
+ buffer.toString(StandardCharsets.UTF_8).strip() + ")");
|
||||||
|
t.line("A caller that only looks at the return value cannot tell these two cases apart.");
|
||||||
|
assertEquals(fromRealZero, fromNothing);
|
||||||
|
|
||||||
|
SinglyLinkedList list = new SinglyLinkedList();
|
||||||
|
list.addFirst(0);
|
||||||
|
t.line("this module, list holding 0: removeFirst() returned " + list.removeFirst());
|
||||||
|
NoSuchElementException e = assertThrows(NoSuchElementException.class, list::removeFirst);
|
||||||
|
t.line("this module, now empty: removeFirst() throws " + e.getClass().getSimpleName() + ": " + e.getMessage());
|
||||||
|
assertNotEquals(0, e.getMessage().length());
|
||||||
|
t.flush();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
package com.ankurm.interviewlab.linkedlist;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
import com.ankurm.interviewlab.linkedlist.support.Transcript;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.IdentityHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
class MiddleAndCycleTest {
|
||||||
|
@Test
|
||||||
|
void middleWithSlowAndFastPointers() {
|
||||||
|
Transcript t = Transcript.start("05-middle-and-cycle.txt", "Middle node and cycle detection with a slow and a fast pointer");
|
||||||
|
t.line("Middle node of 1 -> 2 -> ... -> n (for even n, the second of the two middles):");
|
||||||
|
for (int n = 1; n <= 8; n++) {
|
||||||
|
int[] values = new int[n];
|
||||||
|
for (int i = 0; i < n; i++) {
|
||||||
|
values[i] = i + 1;
|
||||||
|
}
|
||||||
|
int middleValue = LinkedListProblems.middle(ListNode.of(values)).val;
|
||||||
|
assertEquals(values[BruteForce.middleIndex(n)], middleValue);
|
||||||
|
t.line(String.format(" n = %d -> middle value %d (index %d)", n, middleValue, BruteForce.middleIndex(n)));
|
||||||
|
}
|
||||||
|
t.blank();
|
||||||
|
|
||||||
|
t.line("Floyd's algorithm on 3 -> 2 -> 0 -> -4 whose last node links back to index 1:");
|
||||||
|
List<String> trace = DryRuns.floyd(new int[] {3, 2, 0, -4}, 1);
|
||||||
|
for (String line : trace) {
|
||||||
|
t.line(" " + line);
|
||||||
|
}
|
||||||
|
ListNode cyclic = ListNode.withCycle(new int[] {3, 2, 0, -4}, 1);
|
||||||
|
assertTrue(LinkedListProblems.hasCycle(cyclic));
|
||||||
|
assertEquals(2, LinkedListProblems.cycleStart(cyclic).val);
|
||||||
|
assertEquals(3, LinkedListProblems.cycleLength(cyclic));
|
||||||
|
t.blank();
|
||||||
|
t.line("cycleStart value = " + LinkedListProblems.cycleStart(cyclic).val + ", cycleLength = " + LinkedListProblems.cycleLength(cyclic)
|
||||||
|
+ ", hasCycle = " + LinkedListProblems.hasCycle(cyclic));
|
||||||
|
ListNode plain = ListNode.of(3, 2, 0, -4);
|
||||||
|
t.line("plain 3 -> 2 -> 0 -> -4: hasCycle = " + LinkedListProblems.hasCycle(plain) + ", cycleStart = " + LinkedListProblems.cycleStart(plain)
|
||||||
|
+ ", cycleLength = " + LinkedListProblems.cycleLength(plain));
|
||||||
|
assertFalse(LinkedListProblems.hasCycle(plain));
|
||||||
|
assertNull(LinkedListProblems.cycleStart(plain));
|
||||||
|
assertEquals(0, LinkedListProblems.cycleLength(plain));
|
||||||
|
t.blank();
|
||||||
|
|
||||||
|
t.line("Why the second phase works. Tail length mu (nodes before the cycle) and cycle length lambda:");
|
||||||
|
t.line(String.format(" %4s %7s | %-24s | %-18s | %-22s | %s", "mu", "lambda", "steps until they meet", "meet at index", "phase-2 steps", "cycle starts at index"));
|
||||||
|
Pattern meet = Pattern.compile("they meet at index (\\d+) after (\\d+) steps");
|
||||||
|
Pattern again = Pattern.compile("they meet again at index (\\d+) after (\\d+) steps");
|
||||||
|
int checked = 0;
|
||||||
|
for (int mu = 0; mu <= 30; mu++) {
|
||||||
|
for (int lambda = 1; lambda <= 30; lambda++) {
|
||||||
|
int[] values = new int[mu + lambda];
|
||||||
|
for (int i = 0; i < values.length; i++) {
|
||||||
|
values[i] = i;
|
||||||
|
}
|
||||||
|
List<String> run = DryRuns.floyd(values, mu);
|
||||||
|
int meetIndex = -1;
|
||||||
|
int meetSteps = -1;
|
||||||
|
int phase2 = -1;
|
||||||
|
int startIndex = -1;
|
||||||
|
for (String line : run) {
|
||||||
|
Matcher m = meet.matcher(line);
|
||||||
|
if (m.find()) {
|
||||||
|
meetIndex = Integer.parseInt(m.group(1));
|
||||||
|
meetSteps = Integer.parseInt(m.group(2));
|
||||||
|
}
|
||||||
|
Matcher a = again.matcher(line);
|
||||||
|
if (a.find()) {
|
||||||
|
startIndex = Integer.parseInt(a.group(1));
|
||||||
|
phase2 = Integer.parseInt(a.group(2));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
int expectedSteps = Math.max(1, (mu + lambda - 1) / lambda) * lambda; // first multiple of lambda that is >= mu
|
||||||
|
assertEquals(expectedSteps, meetSteps, "mu=" + mu + " lambda=" + lambda);
|
||||||
|
assertEquals(mu, phase2, "phase 2 walks exactly mu steps");
|
||||||
|
assertEquals(mu, startIndex, "and lands on index mu, the first node of the cycle");
|
||||||
|
assertEquals(mu + Math.floorMod(-mu, lambda), meetIndex);
|
||||||
|
checked++;
|
||||||
|
if ((mu == 0 && lambda == 4) || (mu == 3 && lambda == 4) || (mu == 4 && lambda == 4) || (mu == 5 && lambda == 4)
|
||||||
|
|| (mu == 7 && lambda == 3) || (mu == 1 && lambda == 10) || (mu == 30 && lambda == 30)) {
|
||||||
|
t.line(String.format(" %4d %7d | %-24d | %-18d | %-22d | %d", mu, lambda, meetSteps, meetIndex, phase2, startIndex));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.line(" checked all " + checked + " combinations of mu = 0..30 and lambda = 1..30: the formulas held every time.").blank();
|
||||||
|
|
||||||
|
int n = 100_000;
|
||||||
|
int[] values = new int[n];
|
||||||
|
for (int i = 0; i < n; i++) {
|
||||||
|
values[i] = i;
|
||||||
|
}
|
||||||
|
ListNode big = ListNode.withCycle(values, 0);
|
||||||
|
Set<ListNode> seen = Collections.newSetFromMap(new IdentityHashMap<>());
|
||||||
|
ListNode cur = big;
|
||||||
|
while (seen.add(cur)) {
|
||||||
|
cur = cur.next;
|
||||||
|
}
|
||||||
|
assertSame(big, cur);
|
||||||
|
assertTrue(LinkedListProblems.hasCycle(big));
|
||||||
|
t.line("Memory: on a " + n + "-node ring, a set of seen nodes holds " + seen.size() + " entries before it finds the repeat;");
|
||||||
|
t.line("Floyd holds exactly two references (slow and fast) and reaches the same answer: hasCycle = " + LinkedListProblems.hasCycle(big));
|
||||||
|
t.flush();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
package com.ankurm.interviewlab.linkedlist;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
import com.ankurm.interviewlab.linkedlist.support.Transcript;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
class MoreProblemsTest {
|
||||||
|
@Test
|
||||||
|
void mergeAndTheRest() {
|
||||||
|
Transcript t = Transcript.start("06-more-problems.txt", "Merge, remove n-th from end, palindrome, duplicates and intersection");
|
||||||
|
t.line("Merge 1 -> 3 -> 5 and 2 -> 4 -> 6 -> 8 -> 9:");
|
||||||
|
for (String line : DryRuns.merge(new int[] {1, 3, 5}, new int[] {2, 4, 6, 8, 9})) {
|
||||||
|
t.line(" " + line);
|
||||||
|
}
|
||||||
|
assertArrayEquals(new int[] {1, 2, 3, 4, 5, 6, 8, 9},
|
||||||
|
ListNode.toArray(LinkedListProblems.mergeSorted(ListNode.of(1, 3, 5), ListNode.of(2, 4, 6, 8, 9))));
|
||||||
|
t.blank();
|
||||||
|
|
||||||
|
t.line("Remove the n-th node from the end of 1 -> 2 -> 3 -> 4 -> 5:");
|
||||||
|
for (int n = 1; n <= 5; n++) {
|
||||||
|
ListNode out = LinkedListProblems.removeNthFromEnd(ListNode.of(1, 2, 3, 4, 5), n);
|
||||||
|
assertArrayEquals(BruteForce.removeNthFromEnd(new int[] {1, 2, 3, 4, 5}, n), ListNode.toArray(out));
|
||||||
|
t.line(" n = " + n + " -> " + ListNode.show(out));
|
||||||
|
}
|
||||||
|
IllegalArgumentException tooLong = assertThrows(IllegalArgumentException.class,
|
||||||
|
() -> LinkedListProblems.removeNthFromEnd(ListNode.of(1, 2, 3), 4));
|
||||||
|
t.line(" n = 4 on a 3-node list throws " + tooLong.getClass().getSimpleName() + ": " + tooLong.getMessage()).blank();
|
||||||
|
|
||||||
|
t.line("Palindrome check (the list is put back the way it was):");
|
||||||
|
int[][] samples = {{1, 2, 3, 2, 1}, {1, 2, 2, 1}, {1, 2, 3, 4}, {7}, {}};
|
||||||
|
for (int[] sample : samples) {
|
||||||
|
ListNode list = ListNode.of(sample);
|
||||||
|
boolean result = LinkedListProblems.isPalindrome(list);
|
||||||
|
assertEquals(BruteForce.isPalindrome(sample), result);
|
||||||
|
assertArrayEquals(sample, ListNode.toArray(list));
|
||||||
|
t.line(String.format(" %-34s -> %-5s list afterwards: %s", ListNode.show(ListNode.of(sample)), result, ListNode.show(list)));
|
||||||
|
}
|
||||||
|
t.blank();
|
||||||
|
|
||||||
|
ListNode dupes = ListNode.of(1, 1, 2, 3, 3, 3, 4, 4);
|
||||||
|
t.line("Remove duplicates from sorted " + ListNode.show(dupes));
|
||||||
|
ListNode deduped = LinkedListProblems.removeDuplicatesSorted(dupes);
|
||||||
|
assertArrayEquals(new int[] {1, 2, 3, 4}, ListNode.toArray(deduped));
|
||||||
|
t.line(" -> " + ListNode.show(deduped)).blank();
|
||||||
|
|
||||||
|
ListNode shared = ListNode.of(8, 4, 5);
|
||||||
|
ListNode a = new ListNode(4, new ListNode(1, shared));
|
||||||
|
ListNode b = new ListNode(5, new ListNode(6, new ListNode(1, shared)));
|
||||||
|
t.line("Intersection: a = " + ListNode.show(a) + " b = " + ListNode.show(b) + " (the 8 -> 4 -> 5 tail is one shared chain)");
|
||||||
|
ListNode meet = LinkedListProblems.intersection(a, b);
|
||||||
|
assertSame(shared, meet);
|
||||||
|
t.line(" the lists join at the node holding " + meet.val + "; both 1s before it are different nodes with the same value");
|
||||||
|
ListNode separate = ListNode.of(8, 4, 5);
|
||||||
|
assertNull(LinkedListProblems.intersection(a, separate));
|
||||||
|
t.line(" a list that merely has the same values 8 -> 4 -> 5 but its own nodes: intersection = " + LinkedListProblems.intersection(a, separate));
|
||||||
|
assertTrue(Pitfalls.sameNodeByValue(shared, separate));
|
||||||
|
assertFalse(shared == separate);
|
||||||
|
t.flush();
|
||||||
|
}
|
||||||
|
}
|
||||||
+200
@@ -0,0 +1,200 @@
|
|||||||
|
package com.ankurm.interviewlab.linkedlist;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
|
||||||
|
import com.ankurm.interviewlab.linkedlist.support.Transcript;
|
||||||
|
import java.util.NoSuchElementException;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
class NodesAndOperationsTest {
|
||||||
|
@Test
|
||||||
|
void nodesAreJustValuesWithLinks() {
|
||||||
|
Transcript t = Transcript.start("01-nodes-and-links.txt", "A linked list is nodes that point at each other");
|
||||||
|
ListNode c = new ListNode(30);
|
||||||
|
ListNode b = new ListNode(20, c);
|
||||||
|
ListNode a = new ListNode(10, b);
|
||||||
|
assertSame(b, a.next);
|
||||||
|
assertSame(c, a.next.next);
|
||||||
|
assertNull(a.next.next.next);
|
||||||
|
t.line("a.val = " + a.val + " a.next.val = " + a.next.val + " a.next.next.val = " + a.next.next.val
|
||||||
|
+ " a.next.next.next = " + a.next.next.next);
|
||||||
|
t.line("whole list from a: " + ListNode.show(a));
|
||||||
|
t.line("length: " + ListNode.length(a)).blank();
|
||||||
|
|
||||||
|
ListNode fifteen = new ListNode(15, a.next); // 1) the new node points at the node it will precede
|
||||||
|
t.line("new node 15 points at 20: 15 -> " + ListNode.show(fifteen.next));
|
||||||
|
t.line("a still reaches the old chain: " + ListNode.show(a));
|
||||||
|
a.next = fifteen; // 2) the one existing link that has to change
|
||||||
|
t.line("then a.next = the new node: " + ListNode.show(a));
|
||||||
|
assertArrayEquals(new int[] {10, 15, 20, 30}, ListNode.toArray(a));
|
||||||
|
t.line("one new object and one changed link; nothing else moved.").blank();
|
||||||
|
|
||||||
|
t.line("the empty list is null: ListNode.of() == null -> " + (ListNode.of() == null));
|
||||||
|
assertNull(ListNode.of());
|
||||||
|
t.flush();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void operationsAndTheirCosts() {
|
||||||
|
Transcript t = Transcript.start("02-singly-operations.txt", "SinglyLinkedList: operations, errors and the links followed (hops)");
|
||||||
|
SinglyLinkedList list = new SinglyLinkedList();
|
||||||
|
list.addLast(10);
|
||||||
|
t.line("addLast(10) -> " + list);
|
||||||
|
list.addLast(30);
|
||||||
|
t.line("addLast(30) -> " + list);
|
||||||
|
list.add(1, 20);
|
||||||
|
t.line("add(1, 20) -> " + list);
|
||||||
|
list.addFirst(5);
|
||||||
|
t.line("addFirst(5) -> " + list);
|
||||||
|
int removed = list.remove(2);
|
||||||
|
t.line("remove(2) -> removed " + removed + ", list " + list);
|
||||||
|
assertEquals(20, removed);
|
||||||
|
removed = list.removeLast();
|
||||||
|
t.line("removeLast() -> removed " + removed + ", list " + list);
|
||||||
|
assertEquals(30, removed);
|
||||||
|
removed = list.removeFirst();
|
||||||
|
t.line("removeFirst() -> removed " + removed + ", list " + list);
|
||||||
|
assertEquals(5, removed);
|
||||||
|
t.line("indexOf(10) -> " + list.indexOf(10) + " indexOf(99) -> " + list.indexOf(99)).blank();
|
||||||
|
|
||||||
|
SinglyLinkedList empty = new SinglyLinkedList();
|
||||||
|
NoSuchElementException e1 = assertThrows(NoSuchElementException.class, empty::removeFirst);
|
||||||
|
IndexOutOfBoundsException e2 = assertThrows(IndexOutOfBoundsException.class, () -> list.get(5));
|
||||||
|
t.line("empty.removeFirst() throws " + e1.getClass().getSimpleName() + ": " + e1.getMessage());
|
||||||
|
t.line("list.get(5) throws " + e2.getClass().getSimpleName() + ": " + e2.getMessage()).blank();
|
||||||
|
|
||||||
|
t.line("Links followed (hops) per operation, on a list that already holds n values:");
|
||||||
|
t.line(String.format("%6s | %-9s | %-16s | %-14s | %-10s | %-9s | %-11s | %-12s",
|
||||||
|
"n", "addFirst", "addLast no tail", "addLast + tail", "get(n/2)", "indexOf(last)", "removeFirst", "removeLast"));
|
||||||
|
for (int n : new int[] {10, 100, 1000}) {
|
||||||
|
SinglyLinkedList noTail = new SinglyLinkedList(false);
|
||||||
|
SinglyLinkedList tail = new SinglyLinkedList(true);
|
||||||
|
for (int i = 0; i < n; i++) {
|
||||||
|
noTail.addLast(i);
|
||||||
|
tail.addLast(i);
|
||||||
|
}
|
||||||
|
long buildNoTail = noTail.hops();
|
||||||
|
long buildTail = tail.hops();
|
||||||
|
assertEquals((long) (n - 1) * (n - 2) / 2, buildNoTail);
|
||||||
|
assertEquals(0, buildTail);
|
||||||
|
|
||||||
|
long[] cost = new long[6];
|
||||||
|
tail.resetHops();
|
||||||
|
tail.addFirst(-1);
|
||||||
|
cost[0] = tail.hops();
|
||||||
|
tail.removeFirst();
|
||||||
|
tail.resetHops();
|
||||||
|
tail.get(n / 2);
|
||||||
|
cost[3] = tail.hops();
|
||||||
|
tail.resetHops();
|
||||||
|
tail.indexOf(n - 1);
|
||||||
|
cost[4] = tail.hops();
|
||||||
|
tail.resetHops();
|
||||||
|
tail.removeFirst();
|
||||||
|
cost[5] = tail.hops();
|
||||||
|
tail.addFirst(0);
|
||||||
|
tail.resetHops();
|
||||||
|
tail.removeLast();
|
||||||
|
long removeLast = tail.hops();
|
||||||
|
assertEquals(0, cost[0]);
|
||||||
|
assertEquals(n / 2, cost[3]);
|
||||||
|
assertEquals(n - 1, cost[4]);
|
||||||
|
assertEquals(0, cost[5]);
|
||||||
|
assertEquals(n - 2, removeLast);
|
||||||
|
t.line(String.format("%6d | %-9d | %-16d | %-14d | %-10d | %-13d | %-11d | %-12d",
|
||||||
|
n, cost[0], buildNoTail, buildTail, cost[3], cost[4], cost[5], removeLast));
|
||||||
|
}
|
||||||
|
t.line("(\"addLast no tail\" and \"addLast + tail\" are the total hops to build the whole list of n by repeated addLast.)");
|
||||||
|
t.flush();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void deleteDryRun() {
|
||||||
|
Transcript t = Transcript.start("03-delete-dry-run.txt", "Deleting from a singly linked list: which one pointer changes");
|
||||||
|
t.line("remove the node at index 2 from 10 -> 20 -> 30 -> 40:");
|
||||||
|
for (String line : DryRuns.removeAt(2, 10, 20, 30, 40)) {
|
||||||
|
t.line(" " + line);
|
||||||
|
}
|
||||||
|
t.blank();
|
||||||
|
SinglyLinkedList list = new SinglyLinkedList();
|
||||||
|
for (int v : new int[] {10, 20, 30}) {
|
||||||
|
list.addLast(v);
|
||||||
|
}
|
||||||
|
t.line("removing the head has no node before it, so the head variable itself changes:");
|
||||||
|
t.line(" before: head -> " + ListNode.show(list.head()));
|
||||||
|
list.removeFirst();
|
||||||
|
t.line(" head = head.next");
|
||||||
|
t.line(" after: head -> " + ListNode.show(list.head()));
|
||||||
|
assertArrayEquals(new int[] {20, 30}, list.toArray());
|
||||||
|
t.blank();
|
||||||
|
t.line("removing the tail needs the node before it, so it must be found by walking (and then tail moves back):");
|
||||||
|
SinglyLinkedList five = new SinglyLinkedList();
|
||||||
|
for (int v : new int[] {10, 20, 30, 40, 50}) {
|
||||||
|
five.addLast(v);
|
||||||
|
}
|
||||||
|
five.resetHops();
|
||||||
|
int removed = five.removeLast();
|
||||||
|
t.line(" list 10, 20, 30, 40, 50: removeLast() returned " + removed + " after following " + five.hops()
|
||||||
|
+ " links; list is now " + five);
|
||||||
|
assertEquals(50, removed);
|
||||||
|
assertEquals(3, five.hops());
|
||||||
|
t.flush();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void reverseDryRun() {
|
||||||
|
Transcript t = Transcript.start("04-reverse-dry-run.txt", "Reversing 1 -> 2 -> 3 -> 4 with three pointers");
|
||||||
|
for (String line : DryRuns.reverse(1, 2, 3, 4)) {
|
||||||
|
t.line(line);
|
||||||
|
}
|
||||||
|
ListNode r = LinkedListProblems.reverseIterative(ListNode.of(1, 2, 3, 4));
|
||||||
|
assertArrayEquals(new int[] {4, 3, 2, 1}, ListNode.toArray(r));
|
||||||
|
t.blank();
|
||||||
|
t.line("recursive version on the same list: " + ListNode.show(LinkedListProblems.reverseRecursive(ListNode.of(1, 2, 3, 4))));
|
||||||
|
assertArrayEquals(new int[] {4, 3, 2, 1}, ListNode.toArray(LinkedListProblems.reverseRecursive(ListNode.of(1, 2, 3, 4))));
|
||||||
|
t.blank();
|
||||||
|
|
||||||
|
int[] big = new int[1_000_000];
|
||||||
|
for (int i = 0; i < big.length; i++) {
|
||||||
|
big[i] = i;
|
||||||
|
}
|
||||||
|
ListNode million = LinkedListProblems.reverseIterative(ListNode.of(big));
|
||||||
|
assertEquals(999_999, million.val);
|
||||||
|
t.line("iterative, 1,000,000 nodes: first value after reversing = " + million.val + " (no problem)");
|
||||||
|
|
||||||
|
String small = runWithSmallStack(1_000);
|
||||||
|
String large = runWithSmallStack(1_000_000);
|
||||||
|
assertEquals("ok", small);
|
||||||
|
assertEquals("StackOverflowError", large);
|
||||||
|
t.line("recursive, 1,000 nodes on a 1 MB thread stack: " + small);
|
||||||
|
t.line("recursive, 1,000,000 nodes on a 1 MB thread stack: " + large);
|
||||||
|
t.flush();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String runWithSmallStack(int n) {
|
||||||
|
String[] result = new String[1];
|
||||||
|
int[] values = new int[n];
|
||||||
|
for (int i = 0; i < n; i++) {
|
||||||
|
values[i] = i;
|
||||||
|
}
|
||||||
|
Thread thread = new Thread(null, () -> {
|
||||||
|
try {
|
||||||
|
LinkedListProblems.reverseRecursive(ListNode.of(values));
|
||||||
|
result[0] = "ok";
|
||||||
|
} catch (StackOverflowError e) {
|
||||||
|
result[0] = "StackOverflowError";
|
||||||
|
}
|
||||||
|
}, "deep-recursion", 1L << 20);
|
||||||
|
thread.start();
|
||||||
|
try {
|
||||||
|
thread.join();
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
}
|
||||||
|
return result[0];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
package com.ankurm.interviewlab.linkedlist;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
import com.ankurm.interviewlab.linkedlist.support.Transcript;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
class PitfallsTest {
|
||||||
|
@Test
|
||||||
|
void theMistakesPeopleActuallyMake() {
|
||||||
|
Transcript t = Transcript.start("12-pitfalls.txt", "Five plausible mistakes, each run for real");
|
||||||
|
|
||||||
|
t.line("1. Reverse that reads cur.next after overwriting it, on 1 -> 2 -> 3 -> 4:");
|
||||||
|
ListNode lost = Pitfalls.reverseThatLosesTheRest(ListNode.of(1, 2, 3, 4));
|
||||||
|
t.line(" wrong: " + ListNode.show(lost));
|
||||||
|
t.line(" correct: " + ListNode.show(LinkedListProblems.reverseIterative(ListNode.of(1, 2, 3, 4))));
|
||||||
|
assertArrayEquals(new int[] {1}, ListNode.toArray(lost));
|
||||||
|
t.blank();
|
||||||
|
|
||||||
|
t.line("2. Remove the value 1 from 1 -> 2 -> 3, looking only one node ahead:");
|
||||||
|
ListNode unchanged = Pitfalls.removeValueIgnoringHead(ListNode.of(1, 2, 3), 1);
|
||||||
|
t.line(" wrong: " + ListNode.show(unchanged) + " (nothing was removed, and no error)");
|
||||||
|
t.line(" with a dummy node in front: " + ListNode.show(Pitfalls.removeValue(ListNode.of(1, 2, 3), 1)));
|
||||||
|
assertArrayEquals(new int[] {1, 2, 3}, ListNode.toArray(unchanged));
|
||||||
|
assertArrayEquals(new int[] {2, 3}, ListNode.toArray(Pitfalls.removeValue(ListNode.of(1, 2, 3), 1)));
|
||||||
|
t.blank();
|
||||||
|
|
||||||
|
t.line("3. Cycle check that tests fast but not fast.next, on the plain list 1 -> 2 -> 3:");
|
||||||
|
NullPointerException npe = assertThrows(NullPointerException.class, () -> Pitfalls.hasCycleThatThrows(ListNode.of(1, 2, 3)));
|
||||||
|
t.line(" wrong: throws " + npe.getClass().getSimpleName());
|
||||||
|
t.line(" correct: hasCycle = " + LinkedListProblems.hasCycle(ListNode.of(1, 2, 3)));
|
||||||
|
assertFalse(LinkedListProblems.hasCycle(ListNode.of(1, 2, 3)));
|
||||||
|
t.blank();
|
||||||
|
|
||||||
|
t.line("4. Merge that forgets to attach what is left, 1 -> 3 -> 5 and 2 -> 4 -> 6 -> 7 -> 8:");
|
||||||
|
ListNode dropped = Pitfalls.mergeThatDropsTheTail(ListNode.of(1, 3, 5), ListNode.of(2, 4, 6, 7, 8));
|
||||||
|
t.line(" wrong: " + ListNode.show(dropped));
|
||||||
|
t.line(" correct: " + ListNode.show(LinkedListProblems.mergeSorted(ListNode.of(1, 3, 5), ListNode.of(2, 4, 6, 7, 8))));
|
||||||
|
assertArrayEquals(new int[] {1, 2, 3, 4, 5}, ListNode.toArray(dropped));
|
||||||
|
t.blank();
|
||||||
|
|
||||||
|
t.line("5. Comparing nodes by value when the question is about identity (the intersection problem):");
|
||||||
|
ListNode one = ListNode.of(8, 4, 5);
|
||||||
|
ListNode two = ListNode.of(8, 4, 5);
|
||||||
|
t.line(" two separate lists 8 -> 4 -> 5: same value at the head? " + Pitfalls.sameNodeByValue(one, two)
|
||||||
|
+ " same node? " + (one == two));
|
||||||
|
assertTrue(Pitfalls.sameNodeByValue(one, two));
|
||||||
|
assertFalse(one == two);
|
||||||
|
t.blank();
|
||||||
|
|
||||||
|
t.line("Printing a list that has a cycle never ends, so ListNode.show stops after 12 nodes:");
|
||||||
|
ListNode ring = ListNode.withCycle(new int[] {1, 2, 3}, 1);
|
||||||
|
t.line(" " + ListNode.show(ring));
|
||||||
|
assertEquals("1 -> 2 -> 3 -> 2 -> 3 -> 2 -> 3 -> 2 -> 3 -> 2 -> 3 -> 2 -> ...", ListNode.show(ring));
|
||||||
|
t.flush();
|
||||||
|
}
|
||||||
|
}
|
||||||
+290
@@ -0,0 +1,290 @@
|
|||||||
|
package com.ankurm.interviewlab.linkedlist;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||||
|
|
||||||
|
import com.ankurm.interviewlab.linkedlist.support.Transcript;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Random;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
/** Seeded random checks: every list class against java.util.ArrayList, every problem against its brute-force twin. */
|
||||||
|
class RandomAgreementTest {
|
||||||
|
private static final long SEED = 2026L;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void listsAgreeWithArrayList() {
|
||||||
|
Transcript t = Transcript.start("10-random-agreement.txt", "Seeded random operations, compared with java.util.ArrayList after every step");
|
||||||
|
t.line("seed " + SEED + ", 2,000 sequences of 100 operations per class, each step compared with the reference").blank();
|
||||||
|
Random rnd = new Random(SEED);
|
||||||
|
|
||||||
|
long singlyChecks = 0;
|
||||||
|
for (int seq = 0; seq < 2000; seq++) {
|
||||||
|
SinglyLinkedList list = new SinglyLinkedList(seq % 2 == 0);
|
||||||
|
List<Integer> ref = new ArrayList<>();
|
||||||
|
for (int op = 0; op < 100; op++) {
|
||||||
|
int v = rnd.nextInt(50);
|
||||||
|
switch (rnd.nextInt(8)) {
|
||||||
|
case 0 -> {
|
||||||
|
list.addFirst(v);
|
||||||
|
ref.add(0, v);
|
||||||
|
}
|
||||||
|
case 1 -> {
|
||||||
|
list.addLast(v);
|
||||||
|
ref.add(v);
|
||||||
|
}
|
||||||
|
case 2 -> {
|
||||||
|
int i = rnd.nextInt(ref.size() + 1);
|
||||||
|
list.add(i, v);
|
||||||
|
ref.add(i, v);
|
||||||
|
}
|
||||||
|
case 3 -> {
|
||||||
|
if (!ref.isEmpty()) {
|
||||||
|
int i = rnd.nextInt(ref.size());
|
||||||
|
int expected = ref.remove(i);
|
||||||
|
assertEquals(expected, list.remove(i));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case 4 -> {
|
||||||
|
if (!ref.isEmpty()) {
|
||||||
|
int expected = ref.remove(0);
|
||||||
|
assertEquals(expected, list.removeFirst());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case 5 -> {
|
||||||
|
if (!ref.isEmpty()) {
|
||||||
|
int expected = ref.remove(ref.size() - 1);
|
||||||
|
assertEquals(expected, list.removeLast());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case 6 -> {
|
||||||
|
if (!ref.isEmpty()) {
|
||||||
|
int i = rnd.nextInt(ref.size());
|
||||||
|
assertEquals(ref.get(i), list.get(i));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
default -> assertEquals(ref.indexOf(v), list.indexOf(v));
|
||||||
|
}
|
||||||
|
assertEquals(ref.toString(), list.toString());
|
||||||
|
assertEquals(ref.size(), list.size());
|
||||||
|
singlyChecks++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.line(String.format("%-22s %,d steps compared, 0 disagreements", "SinglyLinkedList", singlyChecks));
|
||||||
|
|
||||||
|
long doublyChecks = 0;
|
||||||
|
for (int seq = 0; seq < 2000; seq++) {
|
||||||
|
DoublyLinkedList list = new DoublyLinkedList();
|
||||||
|
List<Integer> ref = new ArrayList<>();
|
||||||
|
for (int op = 0; op < 100; op++) {
|
||||||
|
int v = rnd.nextInt(50);
|
||||||
|
switch (rnd.nextInt(11)) {
|
||||||
|
case 0 -> {
|
||||||
|
list.addFirst(v);
|
||||||
|
ref.add(0, v);
|
||||||
|
}
|
||||||
|
case 1 -> {
|
||||||
|
list.addLast(v);
|
||||||
|
ref.add(v);
|
||||||
|
}
|
||||||
|
case 2 -> {
|
||||||
|
int i = rnd.nextInt(ref.size() + 1);
|
||||||
|
list.add(i, v);
|
||||||
|
ref.add(i, v);
|
||||||
|
}
|
||||||
|
case 3 -> {
|
||||||
|
if (!ref.isEmpty()) {
|
||||||
|
int i = rnd.nextInt(ref.size());
|
||||||
|
int expected = ref.remove(i);
|
||||||
|
assertEquals(expected, list.remove(i));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case 4 -> {
|
||||||
|
if (!ref.isEmpty()) {
|
||||||
|
int expected = ref.remove(0);
|
||||||
|
assertEquals(expected, list.removeFirst());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case 5 -> {
|
||||||
|
if (!ref.isEmpty()) {
|
||||||
|
int expected = ref.remove(ref.size() - 1);
|
||||||
|
assertEquals(expected, list.removeLast());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case 6 -> {
|
||||||
|
if (!ref.isEmpty()) {
|
||||||
|
int i = rnd.nextInt(ref.size());
|
||||||
|
assertEquals(ref.get(i), list.get(i));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case 7 -> {
|
||||||
|
if (!ref.isEmpty()) {
|
||||||
|
int i = rnd.nextInt(ref.size());
|
||||||
|
list.addAfter(list.nodeAt(i), v);
|
||||||
|
ref.add(i + 1, v);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case 8 -> {
|
||||||
|
if (!ref.isEmpty()) {
|
||||||
|
int i = rnd.nextInt(ref.size());
|
||||||
|
list.addBefore(list.nodeAt(i), v);
|
||||||
|
ref.add(i, v);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case 9 -> {
|
||||||
|
if (!ref.isEmpty()) {
|
||||||
|
int i = rnd.nextInt(ref.size());
|
||||||
|
int expected = ref.remove(i);
|
||||||
|
assertEquals(expected, list.remove(list.nodeAt(i)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
default -> {
|
||||||
|
if (!ref.isEmpty()) {
|
||||||
|
list.addAfter(list.last(), v);
|
||||||
|
ref.add(v);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertEquals(ref.toString(), list.toString());
|
||||||
|
int[] backwards = new int[ref.size()];
|
||||||
|
for (int i = 0; i < backwards.length; i++) {
|
||||||
|
backwards[i] = ref.get(ref.size() - 1 - i);
|
||||||
|
}
|
||||||
|
assertArrayEquals(backwards, list.toArrayReversed());
|
||||||
|
doublyChecks++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.line(String.format("%-22s %,d steps compared (forward and backward), 0 disagreements", "DoublyLinkedList", doublyChecks));
|
||||||
|
t.flush();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void problemsAgreeWithBruteForce() {
|
||||||
|
Transcript t = Transcript.start("11-problems-agreement.txt", "Every problem against an obviously-correct brute-force version on seeded random lists");
|
||||||
|
t.line("seed " + SEED + ", 5,000 random cases per problem").blank();
|
||||||
|
Random rnd = new Random(SEED);
|
||||||
|
int cases = 5000;
|
||||||
|
t.line(String.format("%-38s %8s %s", "problem", "cases", "disagreements"));
|
||||||
|
for (String name : new String[] {"reverse (iterative, recursive)", "middle", "mergeSorted", "removeNthFromEnd", "isPalindrome",
|
||||||
|
"removeDuplicatesSorted", "hasCycle / cycleStart / cycleLength", "intersection"}) {
|
||||||
|
int disagreements = 0;
|
||||||
|
for (int c = 0; c < cases; c++) {
|
||||||
|
switch (name.substring(0, 5)) {
|
||||||
|
case "rever" -> {
|
||||||
|
int[] v = randomValues(rnd, rnd.nextInt(13), 7);
|
||||||
|
int[] want = BruteForce.reverse(v);
|
||||||
|
if (!Arrays.equals(want, ListNode.toArray(LinkedListProblems.reverseIterative(ListNode.of(v))))
|
||||||
|
|| !Arrays.equals(want, ListNode.toArray(LinkedListProblems.reverseRecursive(ListNode.of(v))))) {
|
||||||
|
disagreements++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case "middl" -> {
|
||||||
|
int[] v = randomValues(rnd, 1 + rnd.nextInt(12), 100);
|
||||||
|
if (LinkedListProblems.middle(ListNode.of(v)).val != v[BruteForce.middleIndex(v.length)]) {
|
||||||
|
disagreements++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case "merge" -> {
|
||||||
|
int[] a = sorted(randomValues(rnd, rnd.nextInt(9), 10));
|
||||||
|
int[] b = sorted(randomValues(rnd, rnd.nextInt(9), 10));
|
||||||
|
if (!Arrays.equals(BruteForce.mergeSorted(a, b),
|
||||||
|
ListNode.toArray(LinkedListProblems.mergeSorted(ListNode.of(a), ListNode.of(b))))) {
|
||||||
|
disagreements++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case "remov" -> {
|
||||||
|
if (name.startsWith("removeNth")) {
|
||||||
|
int[] v = randomValues(rnd, 1 + rnd.nextInt(12), 20);
|
||||||
|
int n = 1 + rnd.nextInt(v.length);
|
||||||
|
if (!Arrays.equals(BruteForce.removeNthFromEnd(v, n),
|
||||||
|
ListNode.toArray(LinkedListProblems.removeNthFromEnd(ListNode.of(v), n)))) {
|
||||||
|
disagreements++;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
int[] v = sorted(randomValues(rnd, rnd.nextInt(13), 5));
|
||||||
|
if (!Arrays.equals(BruteForce.removeDuplicatesSorted(v),
|
||||||
|
ListNode.toArray(LinkedListProblems.removeDuplicatesSorted(ListNode.of(v))))) {
|
||||||
|
disagreements++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case "isPal" -> {
|
||||||
|
int[] half = randomValues(rnd, rnd.nextInt(7), 4);
|
||||||
|
int[] v;
|
||||||
|
if (rnd.nextBoolean()) {
|
||||||
|
int mid = rnd.nextInt(2); // 0 = even palindrome, 1 = odd palindrome
|
||||||
|
v = new int[half.length * 2 + mid];
|
||||||
|
for (int i = 0; i < half.length; i++) {
|
||||||
|
v[i] = half[i];
|
||||||
|
v[v.length - 1 - i] = half[i];
|
||||||
|
}
|
||||||
|
if (mid == 1) {
|
||||||
|
v[half.length] = rnd.nextInt(4);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
v = randomValues(rnd, rnd.nextInt(10), 3);
|
||||||
|
}
|
||||||
|
ListNode list = ListNode.of(v);
|
||||||
|
if (LinkedListProblems.isPalindrome(list) != BruteForce.isPalindrome(v) || !Arrays.equals(v, ListNode.toArray(list))) {
|
||||||
|
disagreements++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case "hasCy" -> {
|
||||||
|
int[] v = randomValues(rnd, 1 + rnd.nextInt(12), 100);
|
||||||
|
int at = rnd.nextInt(v.length + 1) - 1; // -1 means no cycle
|
||||||
|
ListNode list = ListNode.withCycle(v, at);
|
||||||
|
ListNode wantStart = BruteForce.cycleStart(list);
|
||||||
|
int wantLength = at < 0 ? 0 : v.length - at;
|
||||||
|
if (LinkedListProblems.hasCycle(list) != BruteForce.hasCycle(list)
|
||||||
|
|| LinkedListProblems.cycleStart(list) != wantStart
|
||||||
|
|| LinkedListProblems.cycleLength(list) != wantLength) {
|
||||||
|
disagreements++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
default -> {
|
||||||
|
ListNode shared = ListNode.of(randomValues(rnd, rnd.nextInt(6), 5));
|
||||||
|
ListNode a = prefixThen(randomValues(rnd, rnd.nextInt(6), 5), shared);
|
||||||
|
ListNode b = prefixThen(randomValues(rnd, rnd.nextInt(6), 5), shared);
|
||||||
|
if (LinkedListProblems.intersection(a, b) != BruteForce.intersection(a, b)) {
|
||||||
|
disagreements++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertEquals(0, disagreements, name);
|
||||||
|
t.line(String.format("%-38s %,8d %d", name, cases, disagreements));
|
||||||
|
}
|
||||||
|
assertSame(null, LinkedListProblems.intersection(null, null));
|
||||||
|
t.flush();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ListNode prefixThen(int[] prefix, ListNode rest) {
|
||||||
|
if (prefix.length == 0) {
|
||||||
|
return rest;
|
||||||
|
}
|
||||||
|
ListNode head = ListNode.of(prefix);
|
||||||
|
ListNode last = head;
|
||||||
|
while (last.next != null) {
|
||||||
|
last = last.next;
|
||||||
|
}
|
||||||
|
last.next = rest;
|
||||||
|
return head;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int[] randomValues(Random rnd, int n, int bound) {
|
||||||
|
int[] v = new int[n];
|
||||||
|
for (int i = 0; i < n; i++) {
|
||||||
|
v[i] = rnd.nextInt(bound);
|
||||||
|
}
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int[] sorted(int[] v) {
|
||||||
|
int[] copy = v.clone();
|
||||||
|
Arrays.sort(copy);
|
||||||
|
return copy;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
package com.ankurm.interviewlab.linkedlist.support;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.UncheckedIOException;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/** Writes output/NN-*.txt while the calling test asserts the same numbers it prints. */
|
||||||
|
public final class Transcript {
|
||||||
|
private final Path path;
|
||||||
|
private final List<String> lines = new ArrayList<>();
|
||||||
|
|
||||||
|
private Transcript(Path path, String header) {
|
||||||
|
this.path = path;
|
||||||
|
lines.add(header);
|
||||||
|
lines.add("=".repeat(Math.min(header.length(), 100)));
|
||||||
|
lines.add("");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Transcript start(String fileName, String header) {
|
||||||
|
Path dir = Path.of("output");
|
||||||
|
try {
|
||||||
|
Files.createDirectories(dir);
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new UncheckedIOException(e);
|
||||||
|
}
|
||||||
|
return new Transcript(dir.resolve(fileName), header);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Transcript line(String text) { lines.add(text); return this; }
|
||||||
|
public Transcript blank() { lines.add(""); return this; }
|
||||||
|
|
||||||
|
public void flush() {
|
||||||
|
try {
|
||||||
|
Files.write(path, (String.join("\n", lines) + "\n").getBytes(StandardCharsets.UTF_8));
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new UncheckedIOException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,178 @@
|
|||||||
|
--- Doubly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Display list
|
||||||
|
4. Search
|
||||||
|
5. Exit
|
||||||
|
Select option: 1
|
||||||
|
1. Insert at first
|
||||||
|
2. Insert at last
|
||||||
|
3. Insert after position
|
||||||
|
4. Insert before position
|
||||||
|
Select: 1
|
||||||
|
Enter element: 20
|
||||||
|
|
||||||
|
--- Doubly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Display list
|
||||||
|
4. Search
|
||||||
|
5. Exit
|
||||||
|
Select option: 1
|
||||||
|
1. Insert at first
|
||||||
|
2. Insert at last
|
||||||
|
3. Insert after position
|
||||||
|
4. Insert before position
|
||||||
|
Select: 1
|
||||||
|
Enter element: 40
|
||||||
|
|
||||||
|
--- Doubly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Display list
|
||||||
|
4. Search
|
||||||
|
5. Exit
|
||||||
|
Select option: 1
|
||||||
|
1. Insert at first
|
||||||
|
2. Insert at last
|
||||||
|
3. Insert after position
|
||||||
|
4. Insert before position
|
||||||
|
Select: 2
|
||||||
|
Enter element: 60
|
||||||
|
|
||||||
|
--- Doubly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Display list
|
||||||
|
4. Search
|
||||||
|
5. Exit
|
||||||
|
Select option: 1
|
||||||
|
1. Insert at first
|
||||||
|
2. Insert at last
|
||||||
|
3. Insert after position
|
||||||
|
4. Insert before position
|
||||||
|
Select: 3
|
||||||
|
Enter element: 45
|
||||||
|
Enter position: 2
|
||||||
|
|
||||||
|
--- Doubly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Display list
|
||||||
|
4. Search
|
||||||
|
5. Exit
|
||||||
|
Select option: 1
|
||||||
|
1. Insert at first
|
||||||
|
2. Insert at last
|
||||||
|
3. Insert after position
|
||||||
|
4. Insert before position
|
||||||
|
Select: 4
|
||||||
|
Enter element: 65
|
||||||
|
Enter position: 2
|
||||||
|
|
||||||
|
--- Doubly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Display list
|
||||||
|
4. Search
|
||||||
|
5. Exit
|
||||||
|
Select option: 3
|
||||||
|
1. Forward display
|
||||||
|
2. Reverse display
|
||||||
|
Select: 1
|
||||||
|
Forward: 40 65 20 45 60
|
||||||
|
|
||||||
|
--- Doubly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Display list
|
||||||
|
4. Search
|
||||||
|
5. Exit
|
||||||
|
Select option: 3
|
||||||
|
1. Forward display
|
||||||
|
2. Reverse display
|
||||||
|
Select: 2
|
||||||
|
Reverse: 60 45 20 65 40
|
||||||
|
|
||||||
|
--- Doubly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Display list
|
||||||
|
4. Search
|
||||||
|
5. Exit
|
||||||
|
Select option: 2
|
||||||
|
1. Delete first
|
||||||
|
2. Delete last
|
||||||
|
3. Delete at position
|
||||||
|
Select: 1
|
||||||
|
Deleted: 40
|
||||||
|
|
||||||
|
--- Doubly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Display list
|
||||||
|
4. Search
|
||||||
|
5. Exit
|
||||||
|
Select option: 2
|
||||||
|
1. Delete first
|
||||||
|
2. Delete last
|
||||||
|
3. Delete at position
|
||||||
|
Select: 2
|
||||||
|
Deleted: 60
|
||||||
|
|
||||||
|
--- Doubly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Display list
|
||||||
|
4. Search
|
||||||
|
5. Exit
|
||||||
|
Select option: 3
|
||||||
|
1. Forward display
|
||||||
|
2. Reverse display
|
||||||
|
Select: 1
|
||||||
|
Forward: 65 20 45
|
||||||
|
|
||||||
|
--- Doubly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Display list
|
||||||
|
4. Search
|
||||||
|
5. Exit
|
||||||
|
Select option: 4
|
||||||
|
Enter element to search: 20
|
||||||
|
Element found at position: 2
|
||||||
|
|
||||||
|
--- Doubly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Display list
|
||||||
|
4. Search
|
||||||
|
5. Exit
|
||||||
|
Select option: 2
|
||||||
|
1. Delete first
|
||||||
|
2. Delete last
|
||||||
|
3. Delete at position
|
||||||
|
Select: 3
|
||||||
|
Enter position: 2
|
||||||
|
Deleted: 20
|
||||||
|
|
||||||
|
--- Doubly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Display list
|
||||||
|
4. Search
|
||||||
|
5. Exit
|
||||||
|
Select option: 3
|
||||||
|
1. Forward display
|
||||||
|
2. Reverse display
|
||||||
|
Select: 1
|
||||||
|
Forward: 65 45
|
||||||
|
|
||||||
|
--- Doubly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Display list
|
||||||
|
4. Search
|
||||||
|
5. Exit
|
||||||
|
Select option: 5
|
||||||
|
Exiting...
|
||||||
@@ -0,0 +1,170 @@
|
|||||||
|
--- Singly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Search
|
||||||
|
4. Display
|
||||||
|
5. Exit
|
||||||
|
Enter choice: 1
|
||||||
|
1. Insert at position
|
||||||
|
2. Insert at first
|
||||||
|
3. Insert at last
|
||||||
|
Enter choice: 2
|
||||||
|
Enter element: 10
|
||||||
|
|
||||||
|
--- Singly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Search
|
||||||
|
4. Display
|
||||||
|
5. Exit
|
||||||
|
Enter choice: 1
|
||||||
|
1. Insert at position
|
||||||
|
2. Insert at first
|
||||||
|
3. Insert at last
|
||||||
|
Enter choice: 3
|
||||||
|
Enter element: 50
|
||||||
|
|
||||||
|
--- Singly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Search
|
||||||
|
4. Display
|
||||||
|
5. Exit
|
||||||
|
Enter choice: 1
|
||||||
|
1. Insert at position
|
||||||
|
2. Insert at first
|
||||||
|
3. Insert at last
|
||||||
|
Enter choice: 1
|
||||||
|
Enter element: 20
|
||||||
|
Enter position: 2
|
||||||
|
|
||||||
|
--- Singly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Search
|
||||||
|
4. Display
|
||||||
|
5. Exit
|
||||||
|
Enter choice: 1
|
||||||
|
1. Insert at position
|
||||||
|
2. Insert at first
|
||||||
|
3. Insert at last
|
||||||
|
Enter choice: 3
|
||||||
|
Enter element: 90
|
||||||
|
|
||||||
|
--- Singly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Search
|
||||||
|
4. Display
|
||||||
|
5. Exit
|
||||||
|
Enter choice: 4
|
||||||
|
List: 10 20 50 90
|
||||||
|
|
||||||
|
--- Singly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Search
|
||||||
|
4. Display
|
||||||
|
5. Exit
|
||||||
|
Enter choice: 3
|
||||||
|
Enter element to search: 50
|
||||||
|
Element found at position: 3
|
||||||
|
|
||||||
|
--- Singly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Search
|
||||||
|
4. Display
|
||||||
|
5. Exit
|
||||||
|
Enter choice: 3
|
||||||
|
Enter element to search: 1
|
||||||
|
Element not found
|
||||||
|
|
||||||
|
--- Singly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Search
|
||||||
|
4. Display
|
||||||
|
5. Exit
|
||||||
|
Enter choice: 2
|
||||||
|
1. Remove first element
|
||||||
|
2. Remove last element
|
||||||
|
3. Remove element at position
|
||||||
|
Enter choice: 1
|
||||||
|
Removed: 10
|
||||||
|
|
||||||
|
--- Singly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Search
|
||||||
|
4. Display
|
||||||
|
5. Exit
|
||||||
|
Enter choice: 2
|
||||||
|
1. Remove first element
|
||||||
|
2. Remove last element
|
||||||
|
3. Remove element at position
|
||||||
|
Enter choice: 2
|
||||||
|
Removed: 90
|
||||||
|
|
||||||
|
--- Singly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Search
|
||||||
|
4. Display
|
||||||
|
5. Exit
|
||||||
|
Enter choice: 4
|
||||||
|
List: 20 50
|
||||||
|
|
||||||
|
--- Singly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Search
|
||||||
|
4. Display
|
||||||
|
5. Exit
|
||||||
|
Enter choice: 1
|
||||||
|
1. Insert at position
|
||||||
|
2. Insert at first
|
||||||
|
3. Insert at last
|
||||||
|
Enter choice: 3
|
||||||
|
Enter element: 80
|
||||||
|
|
||||||
|
--- Singly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Search
|
||||||
|
4. Display
|
||||||
|
5. Exit
|
||||||
|
Enter choice: 4
|
||||||
|
List: 20 50 80
|
||||||
|
|
||||||
|
--- Singly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Search
|
||||||
|
4. Display
|
||||||
|
5. Exit
|
||||||
|
Enter choice: 2
|
||||||
|
1. Remove first element
|
||||||
|
2. Remove last element
|
||||||
|
3. Remove element at position
|
||||||
|
Enter choice: 3
|
||||||
|
Enter position: 2
|
||||||
|
Removed: 50
|
||||||
|
|
||||||
|
--- Singly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Search
|
||||||
|
4. Display
|
||||||
|
5. Exit
|
||||||
|
Enter choice: 4
|
||||||
|
List: 20 80
|
||||||
|
|
||||||
|
--- Singly Linked List Menu ---
|
||||||
|
1. Insert
|
||||||
|
2. Remove
|
||||||
|
3. Search
|
||||||
|
4. Display
|
||||||
|
5. Exit
|
||||||
|
Enter choice: 5
|
||||||
|
Exiting...
|
||||||
Reference in New Issue
Block a user