File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * 206. Reverse Linked List
3
+ * Given the head of a singly linked list, reverse the list, and return the reversed list.
4
+ *
5
+ * https://leetcode.com/problems/reverse-linked-list/description/
6
+ *
7
+ */
8
+
9
+ /**
10
+ * Definition for singly-linked list.
11
+ * class ListNode {
12
+ * val: number
13
+ * next: ListNode | null
14
+ * constructor(val?: number, next?: ListNode | null) {
15
+ * this.val = (val===undefined ? 0 : val)
16
+ * this.next = (next===undefined ? null : next)
17
+ * }
18
+ * }
19
+ */
20
+
21
+ class ListNode {
22
+ val : number ;
23
+ next : ListNode | null ;
24
+ constructor ( val ?: number , next ?: ListNode | null ) {
25
+ this . val = val === undefined ? 0 : val ;
26
+ this . next = next === undefined ? null : next ;
27
+ }
28
+ }
29
+
30
+ // O(n) time
31
+ // O(1) space
32
+ function reverseList ( head : ListNode | null ) : ListNode | null {
33
+ let prev : ListNode | null = null ;
34
+ let next : ListNode | null = null ;
35
+
36
+ while ( head ) {
37
+ next = head . next ;
38
+ head . next = prev ;
39
+
40
+ prev = head ;
41
+ head = next ;
42
+ }
43
+
44
+ return prev ;
45
+ }
You can’t perform that action at this time.
0 commit comments