forked from ayushi-ras/beginner-contribution-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreverseLinkedList.js
54 lines (43 loc) · 1.27 KB
/
reverseLinkedList.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Definition for singly-linked list.
function ListNode(val) {
this.val = val;
this.next = null;
}
function reverseLinkedList(head) {
let prev = null;
let current = head;
while (current !== null) {
const nextTemp = current.next;
current.next = prev;
prev = current;
current = nextTemp;
}
return prev; // The new head of the reversed list
}
// Helper function to convert an array to a linked list
function arrayToLinkedList(arr) {
if (arr.length === 0) return null;
const head = new ListNode(arr[0]);
let current = head;
for (let i = 1; i < arr.length; i++) {
current.next = new ListNode(arr[i]);
current = current.next;
}
return head;
}
// Helper function to convert a linked list to an array
function linkedListToArray(head) {
const result = [];
let current = head;
while (current !== null) {
result.push(current.val);
current = current.next;
}
return result;
}
// Example usage:
const inputArray = [1, 2, 3, 4, 5];
const inputLinkedList = arrayToLinkedList(inputArray);
const reversedLinkedList = reverseLinkedList(inputLinkedList);
const reversedArray = linkedListToArray(reversedLinkedList);
console.log(reversedArray); // Output: [5, 4, 3, 2, 1]