Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Last active May 7, 2024 16:01
Show Gist options
  • Save tatsuyax25/cf1fe3ef09d1817369145c351580e6f7 to your computer and use it in GitHub Desktop.
Save tatsuyax25/cf1fe3ef09d1817369145c351580e6f7 to your computer and use it in GitHub Desktop.
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var doubleIt = function(head) {
// Initialize a dummy head for the new linked list
var dummyHead = new ListNode(0);
var current = dummyHead;
// Initialize a variable to store the carry
var carry = 0;
// Traverse the linked list from the least significant digit
var node = reverseList(head);
while (node != null || carry > 0) {
// Double the current digit and add the carry
var sum = (node != null ? node.val : 0) * 2 + carry;
// Update the carry
carry = Math.floor(sum / 10);
// Create a new node for the current digit
current.next = new ListNode(sum % 10);
// Move to the next digit
current = current.next;
if (node != null) node = node.next;
}
// Reverse the linked list to get the correct order
return reverseList(dummyHead.next);
};
// Helper function to reverse a linked list
function reverseList(head) {
var prev = null;
var current = head;
while (current != null) {
var nextTemp = current.next;
current.next = prev;
prev = current;
current = nextTemp;
}
return prev;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment