709988. Move Last Element to Front of a Linked List
Easy
Move Last Element to Front of a Linked List
Summary
Given a singly linked list, move the last element to the front of the list. This problem involves working with linked lists and manipulating their structure.
Detailed Explanation
The approach to solve this problem is straightforward: traverse the linked list until you reach the end (i.e., the last node), then reverse the direction of the link for that node to point back to the previous node, effectively moving it to the front. This process can be repeated until the desired result is achieved.
Here's a step-by-step breakdown:
- Initialize a pointer
prevtoNULL, which will keep track of the second-to-last node. - Initialize a pointer
currto the head of the linked list, which will traverse the list. - Traverse the list until you reach the end (i.e.,
curr->next == NULL). This is done by movingcurrone step at a time and updatingprevaccordingly. - Once you've reached the end, reverse the direction of the link for the last node (
curr) to point back toprev. This effectively moves the last element to the front. - Repeat steps 2-4 until the desired result is achieved (i.e., the last element is at the front).
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 prev and curr.
Optimized Solutions
Java
public class Solution {
public void moveLastToFirst(Node head) {
if (head == null || head.next == null) return;
Node prev = null;
Node curr = head;
while (curr.next != null) {
prev = curr;
curr = curr.next;
}
curr.next = head;
head = curr;
}
}