Skip to content

Commit 5274c46

Browse files
committed
Reverse Linked List
1 parent 2a82135 commit 5274c46

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

Reverse Linked List.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/*Reverse a singly linked list.*/
2+
3+
/**
4+
* Definition for singly-linked list.
5+
* function ListNode(val) {
6+
* this.val = val;
7+
* this.next = null;
8+
* }
9+
*/
10+
/**
11+
* @param {ListNode} head
12+
* @return {ListNode}
13+
*/
14+
var reverseList = function(head) {
15+
arr = []
16+
cur = head
17+
while(cur != null){
18+
arr.push(cur.val)
19+
cur = cur.next
20+
}
21+
return arr.reverse()
22+
head = new ListNode(arr[0])
23+
curr = head
24+
for(i=1; i<arr.length-1; i++){
25+
curr.next = new ListNode(arr[i])
26+
curr = curr.next
27+
}
28+
curr.next = null
29+
return head
30+
};

0 commit comments

Comments
 (0)