Commit ddea815
committed
feat(LinkedListDemo): add demo for Java LinkedList operations and complexities
What
- Created `LinkedListDemo` class to demonstrate:
- Adding elements with `add()`, `addFirst()`, and `addLast()`.
- Accessing elements using `get(index)` and `getLast()`.
- Printing the list contents.
- Added comments comparing time complexity with `ArrayList`.
Why
- Show how Java’s `LinkedList` (doubly-linked) differs from `ArrayList` in performance:
- Frequent insertions/deletions → `O(1)` with LinkedList.
- Random access (`get(index)`) → `O(n)` with LinkedList vs `O(1)` in ArrayList.
- Helps learners understand when to use `LinkedList` vs `ArrayList`.
How
- Declared `LinkedList<Integer> linkedList`.
- Added elements: `1, 2, 3`.
- Retrieved an element at index `2` (`linkedList.get(2)` → O(n)).
- Inserted new elements:
- `addLast(4)` → constant time append.
- `addFirst(0)` → constant time prepend.
- Retrieved last element using `getLast()`.
- Printed the list to show final contents.
Logic
1. Start with empty `LinkedList`.
2. Add elements → `[1, 2, 3]`.
3. Access element at index 2 → returns `3`.
4. Add `4` at the end → `[1, 2, 3, 4]`.
5. Add `0` at the beginning → `[0, 1, 2, 3, 4]`.
6. Print → final state shown.
Complexity
- `addFirst()`, `addLast()`, `getFirst()`, `getLast()` → O(1).
- `get(index)`, `remove(index)` → O(n) due to traversal.
- ArrayList contrast:
- Access by index: O(1).
- Insert/remove in middle: O(n) due to shifting elements.
Applications
- Use LinkedList when:
- Insertions/removals happen frequently in middle/start.
- Order of elements matters and random access is not critical.
- Use ArrayList when:
- Random access dominates.
- Insertions/removals mostly at the end.
Notes
- Java’s `LinkedList` is **doubly-linked**, so each node has `next` and `previous` pointers.
- Example also includes commented manual `Node` creation to reinforce internal structure.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 5d6385a commit ddea815
File tree
1 file changed
+38
-0
lines changed- Section 25 Collections Frameworks/List Interface/LinkedList/src
1 file changed
+38
-0
lines changedLines changed: 38 additions & 0 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
| 25 | + | |
| 26 | + | |
| 27 | + | |
| 28 | + | |
| 29 | + | |
| 30 | + | |
| 31 | + | |
| 32 | + | |
| 33 | + | |
| 34 | + | |
| 35 | + | |
| 36 | + | |
| 37 | + | |
| 38 | + | |
0 commit comments