Guided Project: Linked Lists II

Learn advanced linked list operations including insertion and deletion at specific positions.

Insertion at Position

Example Implementation

class Node { int value; Node next; Node(int value) { this.value = value; this.next = null; } } class LinkedList { Node head; int length; public LinkedList() { this.head = null; this.length = 0; } // Add a node to the end of the list public void append(int value) { Node newNode = new Node(value); length++; if (head == null) { head = newNode; return; } Node current = head; while (current.next != null) { current = current.next; } current.next = newNode; } // Insert a node at a specific position public boolean insertAtPosition(int position, int value) { if (position < 0 || position > length) { return false; } Node newNode = new Node(value); if (position == 0) { newNode.next = head; head = newNode; length++; return true; } Node current = head; Node previous = null; int index = 0; while (index < position) { previous = current; current = current.next; index++; } newNode.next = current; previous.next = newNode; length++; return true; } }

Example Usage:

LinkedList list = new LinkedList(); list.append(1); list.append(3); list.append(4); // Insert 2 at position 1 (between 1 and 3) list.insertAtPosition(1, 2); // Output: 1 -> 2 -> 3 -> 4

Deletion at Position

Example Implementation

class LinkedList { // ... previous methods // Remove a node at a specific position public Integer removeAtPosition(int position) { if (head == null || position < 0 || position >= length) { return null; } Node removedNode; if (position == 0) { removedNode = head; head = head.next; length--; return removedNode.value; } Node current = head; Node previous = null; int index = 0; while (index < position) { previous = current; current = current.next; index++; } removedNode = current; previous.next = current.next; length--; return removedNode.value; } }

Example Usage:

LinkedList list = new LinkedList(); list.append(1); list.append(2); list.append(3); list.append(4); // Remove node at position 2 (value 3) Integer removed = list.removeAtPosition(2); System.out.println(removed); // 3 // Output: 1 -> 2 -> 4

Practice Challenges

Now that you've learned how to implement insertion and deletion at specific positions in a linked list, try these practice challenges:

Challenge 1: Reverse a Linked List

Implement a method to reverse a linked list in-place.

class LinkedList { // ... previous methods public void reverse() { // Your code here } }

Challenge 2: Find the Middle Node

Implement a method to find the middle node of a linked list using only one pass.

class LinkedList { // ... previous methods public Node findMiddle() { // Your code here return null; } }

Additional Resources

If you want more practice with linked lists, check out these LeetCode problems: