File tree Expand file tree Collapse file tree 1 file changed +23
-14
lines changed Expand file tree Collapse file tree 1 file changed +23
-14
lines changed Original file line number Diff line number Diff line change 1
-
2
1
/**
2
+ * Given the head of a singly linked list, reverse the list, and return the
3
+ * reversed list.
4
+ *
5
+ * Constraints:
6
+ *
7
+ * The number of nodes in the list is the range [0, 5000].
8
+ * -5000 <= Node.val <= 5000
9
+ *
3
10
* Definition for singly-linked list.
4
11
* struct ListNode {
5
12
* int val;
6
13
* struct ListNode *next;
7
14
* };
15
+ *
16
+ * Space: O(1)
17
+ * Time: O(n)
8
18
*/
9
19
10
-
11
20
struct ListNode * reverseList (struct ListNode * head ){
12
-
13
- if (head == NULL ) {
14
- return NULL ;
15
- } else if (head -> next == NULL ) {
16
- return head ;
21
+ struct ListNode * current = head ;
22
+ struct ListNode * next = NULL ;
23
+ struct ListNode * previous = NULL ;
24
+
25
+ while (current ) {
26
+ next = current -> next ;
27
+ current -> next = previous ;
28
+ previous = current ;
29
+ current = next ;
17
30
}
18
-
19
- struct ListNode * lastNode = reverseList (head -> next );
20
- head -> next -> next = head ;
21
- head -> next = NULL ;
22
- return lastNode ;
23
-
24
- }
31
+
32
+ return previous ;
33
+ }
You can’t perform that action at this time.
0 commit comments