Reverse Linked List problem results
First Blood
Iterative Method.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
{
ListNode* reverseList(ListNode* head) {
if(head == nullptr || head->next == nullptr)
return head;
ListNode* curr = head->next;
ListNode* temp = curr->next;
curr->next = head;
head->next = nullptr;
head = curr;
curr = temp;
while(curr != nullptr)
{
temp = curr->next;
curr->next = head;
head = curr;
curr = temp;
}
return head;
}
}
Double Kill
Iterative Method with simpler code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
ListNode* reverseList(ListNode* head) {
ListNode* temp = nullptr;
ListNode* prev = nullptr;
while(head != nullptr)
{
temp = head->next;
head->next = prev;
prev = head;
head = temp;
}
return prev;
}
}
Triple Kill
Recursive Method.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
ListNode* reverseList(ListNode* head) {
if(head == NULL || head -> next == NULL){
return head;
}
ListNode* reversedListHead = reverseList(head -> next);
head -> next -> next = head;
head -> next = NULL;
return reversedListHead;
}
}