File tree 1 file changed +91
-0
lines changed
1 file changed +91
-0
lines changed Original file line number Diff line number Diff line change
1
+ # 206. Reverse Linked List
2
+
3
+ - Difficulty: Easy.
4
+ - Related Topics: Linked List.
5
+ - Similar Questions: Reverse Linked List II, Binary Tree Upside Down, Palindrome Linked List.
6
+
7
+ ## Problem
8
+
9
+ Reverse a singly linked list.
10
+
11
+ ** Example:**
12
+
13
+ ```
14
+ Input: 1->2->3->4->5->NULL
15
+ Output: 5->4->3->2->1->NULL
16
+ ```
17
+
18
+ ** Follow up:**
19
+
20
+ A linked list can be reversed either iteratively or recursively. Could you implement both?
21
+
22
+ ## Solution 1
23
+
24
+ ``` javascript
25
+ /**
26
+ * Definition for singly-linked list.
27
+ * function ListNode(val) {
28
+ * this.val = val;
29
+ * this.next = null;
30
+ * }
31
+ */
32
+ /**
33
+ * @param {ListNode} head
34
+ * @return {ListNode}
35
+ */
36
+ var reverseList = function (head ) {
37
+ var newHead = null ;
38
+ var tmp = null ;
39
+ while (head) {
40
+ tmp = head .next ;
41
+ head .next = newHead;
42
+ newHead = head;
43
+ head = tmp;
44
+ }
45
+ return newHead;
46
+ };
47
+ ```
48
+
49
+ ** Explain:**
50
+
51
+ nope.
52
+
53
+ ** Complexity:**
54
+
55
+ * Time complexity : O(n).
56
+ * Space complexity : O(1).
57
+
58
+ ## Solution 2
59
+
60
+ ``` javascript
61
+ /**
62
+ * Definition for singly-linked list.
63
+ * function ListNode(val) {
64
+ * this.val = val;
65
+ * this.next = null;
66
+ * }
67
+ */
68
+ /**
69
+ * @param {ListNode} head
70
+ * @return {ListNode}
71
+ */
72
+ var reverseList = function (head ) {
73
+ return reverse (null , head);
74
+ };
75
+
76
+ var reverse = function (newHead , head ) {
77
+ if (! head) return newHead;
78
+ var tmp = head .next ;
79
+ head .next = newHead;
80
+ return reverse (head, tmp);
81
+ };
82
+ ```
83
+
84
+ ** Explain:**
85
+
86
+ nope.
87
+
88
+ ** Complexity:**
89
+
90
+ * Time complexity : O(n).
91
+ * Space complexity : O(n).
You can’t perform that action at this time.
0 commit comments