Reverse a Singly Linked List
Problem
Given the head of a singly linked list, reverse the direction of every next pointer in place and return the new head. Use only constant extra space.
Input
1 → 2 → 3 → nullOutput
3 → 2 → 1 → nulldef reverse_list(head):
prev, curr = None, head
while curr is not None:
nxt = curr.next
curr.next = prev
prev = curr
curr = nxt
return prev
function reverseList(head) {
let prev = null;
let curr = head;
while (curr !== null) {
const next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
}
ListNode* reverseList(ListNode* head) {
ListNode* prev = nullptr;
ListNode* curr = head;
while (curr) {
ListNode* next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}