reverse a singly linked list

here are two versions of the function that reverses a singly linked list, by iteration and recursion respectively.

there should be a better recursion version, I will update it later.

 1 void reverseLinkedList(Node **current){
 2     //this version will change the original list
 3     //iteration version 
 4     Node* pre = nullptr;
 5     while(*current){
 6         Node *temp = *current->next;
 7         *current->next = pre;
 8         pre = *current;
 9         *current = temp;
10     }
11 }
12 
13 void reverseLinkedList(Node **head){
14     //recursion version
15     if (*head == nullptr) return;
16     Node *first = *head;
17     Node *rest = head->next;
18     if (rest == nullptr) return;
19     
20     reverseLinkedList(&rest);
21     first->next->next = first;
22     first->next = nullptr;
23     *head = rest;   //update the new head
24 }

 (Update) this may be a more clear version of recursion method,

1.iterate the list through recursion, reach the last node.take it as the new head

2. add the previous node to the new head, then update the value to *head.

1 void reverseLinkedList(Node **head){
2     //recursion #2
3     if (*head == nullptr || *head->next == nullptr) return;
4     Node *rest = *head->next;
5     *head->next = nullptr;
6     reverseLinkedList(&rest);
7     rest->next = head;
8     *head = rest;
9 }

 

你可能感兴趣的:(reverse a singly linked list)