700006. Reverse alternate nodes in Link List
Medium
Reverse Alternate Nodes in Link List
Slug: given-a-linked-list-reverse-alternate-nodes-and-append-at-the-end
Difficulty: Medium
Id: 700006
Topic Tags: Linked List, Data Structures
Company Tags: Amazon, Walmart
Summary
Given a linked list, reverse alternate nodes and append the remaining nodes at the end. This problem requires manipulating a linked list by reversing every other node.
Detailed Explanation
To solve this problem, we'll first create a new head for the reversed list. Then, we'll iterate through the original list, reversing every other node. For each reversed node, we'll update the next pointer to point to the current node in the original list. Finally, we'll append the remaining nodes at the end.
Here's the step-by-step breakdown:
- Initialize a new head for the reversed list (let's call it
reversedHead). - Set
currentNodeto the head of the original list. - Iterate through the original list until
currentNodeis null:- If
currentNodeis at an even index, reverse its next node and updatenextpointer. - If
currentNodeis at an odd index, move to the next node in the original list.
- If
- When the loop finishes, append the remaining nodes (if any) at the end of the reversed list.
Time complexity: O(n), where n is the number of nodes in the linked list. Space complexity: O(1), as we only use a constant amount of space to store temporary pointers.
Optimized Solutions
Java
public class ListNode {
int val;
ListNode next;
public ListNode(int x) { val = x; }
}
public static ListNode reverseAlternateNodes(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode reversedHead = new ListNode(0);
ListNode currentReversedNode = reversedHead;
ListNode currentOriginalNode = head;
while (currentOriginalNode != null && currentOriginalNode.next != null) {
currentReversedNode.next = new ListNode(currentOriginalNode.val);
currentReversedNode = currentReversedNode.next;
if (currentOriginalNode.val % 2 == 0) {
currentOriginalNode = currentOriginalNode.next;
} else {
currentOriginalNode = currentOriginalNode.next.next;
}
}
// Append remaining nodes
while (currentOriginalNode != null) {
currentReversedNode.next = new ListNode(currentOriginalNode.val);
currentReversedNode = currentReversedNode.next;
currentOriginalNode = currentOriginalNode.next;
}
return reversedHead.next;
}