In-place manipulation of a linked list involves modifying the structure of the list without using extra space. Common operations include reversing, reordering, or merging nodes.
// Reverse a Linked List
public ListNode reverse(ListNode head) {
ListNode prev = null;
while (head != null) {
ListNode next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}
// Reorder a Linked List
public void reorderList(ListNode head) {
if (head == null || head.next == null) return;
// Find the middle of the list
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
// Reverse the second half
ListNode second = reverse(slow.next);
slow.next = null;
// Merge two halves
ListNode first = head;
while (second != null) {
ListNode temp1 = first.next, temp2 = second.next;
first.next = second;
second.next = temp1;
first = temp1;
second = temp2;
}
}
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]