Skip to content

Commit

Permalink
c: 0206-reverse-linked-list: use pointers instead of recursion
Browse files Browse the repository at this point in the history
Recursion is hard to debug and can be difficult to follow.
Using struct pointers is faster and easier to understand.
  • Loading branch information
andrewmustea committed Jan 16, 2023
1 parent c5ec43f commit b43dfb4
Showing 1 changed file with 23 additions and 14 deletions.
37 changes: 23 additions & 14 deletions c/0206-reverse-linked-list.c
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;
}

0 comments on commit b43dfb4

Please sign in to comment.