Created
April 25, 2023 04:10
-
-
Save parkerproject/e2a052b22bdbaa121d2b045f44cf7d7d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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