forked from jyxia/LeetCode-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path206-reversedLinkedList.js
50 lines (46 loc) · 1.18 KB
/
206-reversedLinkedList.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
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
// Iterative way
var reverseList = function(head) {
if (head === null || head.next === null) return head;
var headNext = head.next;
head.next = null;
while (head !== null && headNext !== null) {
// keep a reference of the headNext's next node
var tmp = headNext.next;
headNext.next = head;
head = headNext;
headNext = tmp;
}
return head;
};
// a more concise solution, prevHead eventually wll be the reversed list head
var reverseList = function(head) {
var prevHead = null;
while (head) {
var headNext = head.next;
head.next = prevHead;
prevHead = head;
head = headNext;
}
return prevHead;
};
// recursive way
var reverseList = function(head) {
if (head === null || head.next === null) return head;
var headNext = head.next;
head.next = null;
var nextReversedListHead = reverseList(headNext);
// now headNext is the last node of the reversed List on the right of head!!!
headNext.next = head;
return nextReversedListHead;
};