Skip to content

Instantly share code, notes, and snippets.

@parkerproject
Created April 25, 2023 04:10
Show Gist options
  • Save parkerproject/e2a052b22bdbaa121d2b045f44cf7d7d to your computer and use it in GitHub Desktop.
Save parkerproject/e2a052b22bdbaa121d2b045f44cf7d7d to your computer and use it in GitHub Desktop.
// Definition for singly-linked list
function ListNode(val) {
this.val = val;
this.next = null;
}
// Function to reverse a singly-linked list
function reverseLinkedList(head) {
let prev = null;
let current = head;
let next = null;
while (current !== null) {
next = current.next; // Store the next node in the original list
current.next = prev; // Reverse the current node's next pointer to point to the previous node
prev = current; // Move the previous node to the current node
current = next; // Move the current node to the next node in the original list
}
return prev; // The new head of the reversed list
}
// Example usage:
let list = new ListNode(1);
list.next = new ListNode(2);
list.next.next = new ListNode(3);
list.next.next.next = new ListNode(4);
let reversedList = reverseLinkedList(list);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment