Skip to content

Commit b43dfb4

Browse files
committed
c: 0206-reverse-linked-list: use pointers instead of recursion
Recursion is hard to debug and can be difficult to follow. Using struct pointers is faster and easier to understand.
1 parent c5ec43f commit b43dfb4

File tree

1 file changed

+23
-14
lines changed

1 file changed

+23
-14
lines changed

c/0206-reverse-linked-list.c

Lines changed: 23 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,33 @@
1-
21
/**
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+
*
310
* Definition for singly-linked list.
411
* struct ListNode {
512
* int val;
613
* struct ListNode *next;
714
* };
15+
*
16+
* Space: O(1)
17+
* Time: O(n)
818
*/
919

10-
1120
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;
1730
}
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+
}

0 commit comments

Comments
 (0)