forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
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.
- Loading branch information
1 parent
c5ec43f
commit b43dfb4
Showing
1 changed file
with
23 additions
and
14 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,24 +1,33 @@ | ||
|
||
/** | ||
* Given the head of a singly linked list, reverse the list, and return the | ||
* reversed list. | ||
* | ||
* Constraints: | ||
* | ||
* The number of nodes in the list is the range [0, 5000]. | ||
* -5000 <= Node.val <= 5000 | ||
* | ||
* Definition for singly-linked list. | ||
* struct ListNode { | ||
* int val; | ||
* struct ListNode *next; | ||
* }; | ||
* | ||
* Space: O(1) | ||
* Time: O(n) | ||
*/ | ||
|
||
|
||
struct ListNode* reverseList(struct ListNode* head){ | ||
|
||
if (head == NULL) { | ||
return NULL; | ||
} else if (head -> next == NULL) { | ||
return head; | ||
struct ListNode *current = head; | ||
struct ListNode *next = NULL; | ||
struct ListNode *previous = NULL; | ||
|
||
while (current) { | ||
next = current->next; | ||
current->next = previous; | ||
previous = current; | ||
current = next; | ||
} | ||
|
||
struct ListNode* lastNode = reverseList(head -> next); | ||
head -> next -> next = head; | ||
head -> next = NULL; | ||
return lastNode; | ||
|
||
} | ||
|
||
return previous; | ||
} |