AlgoDaily Solution
1var assert = require('assert');
2
3// iterative
4function reverseList(head) {
5 if (head.length < 2) {
6 return;
7 }
8
9 let newHead = null;
10 while (head != null) {
11 let nextNode = head.next;
12 head.next = newHead;
13 newHead = head;
14 head = nextNode;
15 }
16 return newHead;
17}
18
19// recursive
20function reverseList(head) {
21 if (!head || !head.next) {
22 return head;
23 }
24
25 let rest = reverseList(head.next);
26
27 head.next.next = head;
28 delete head.next;
29 return rest;
30}
31
32function Node(val) {
33 this.val = val;
34 this.next = null;
35}
36
37function LinkedListNode(val) {
38 this.val = val;
39 this.next = null;
40}
41
42var list1 = new LinkedListNode(3);
43var nodes1 = [4, 5, 6, 7, 8, 9, 10];
44createNodes(list1, nodes1);
45
46var list2 = new LinkedListNode(1);
47var nodes2 = [2, 3, 4, 5, 6, 7, 8];
48createNodes(list2, nodes2);
49
50function createNodes(head, nodes) {
51 for (let i = 0; i < nodes.length; i++) {
52 var newNode = new LinkedListNode(nodes[i]);
53 head.next = newNode;
54 head = newNode;
55 }
56}
57
58try {
59 var reversed = reverseList(list1);
60 assert.deepEqual(
61 listToString(reversed),
62 '10 -> 9 -> 8 -> 7 -> 6 -> 5 -> 4 -> 3'
63 );
64
65 console.log(
66 'PASSED: Reversing linked list `3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10` should return `10 -> 9 -> 8 -> 7 -> 6 -> 5 -> 4 -> 3`'
67 );
68} catch (err) {
69 console.log(err);
70}
71
72function listToString(head) {
73 var toPrint = [];
74 var currNode = head;
75 while (currNode) {
76 toPrint.push(currNode.val);
77 currNode = currNode.next;
78 }
79 return toPrint.join(' -> ');
80}
Community Solutions
Community solutions are only available for premium users.
Access all course materials today
The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.
xxxxxxxxxx
57
var assert = require('assert');
function reverseList(head) {
// Fill in this method
return head;
}
function Node(val) {
this.val = val;
this.next = null;
}
function LinkedListNode(val) {
this.val = val;
this.next = null;
}
var list1 = new LinkedListNode(3);
var nodes1 = [4, 5, 6, 7, 8, 9, 10];
createNodes(list1, nodes1);
var list2 = new LinkedListNode(1);
var nodes2 = [2, 3, 4, 5, 6, 7, 8];
createNodes(list2, nodes2);
function createNodes(head, nodes) {
for (let i = 0; i < nodes.length; i++) {
OUTPUT
Results will appear here.