首页 > 其他 > 详细

reverse a singly linked list

时间:2016-02-20 06:59:15      阅读:276      评论:0      收藏:0      [点我收藏+]

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

原文:http://www.cnblogs.com/charmingblog/p/5202580.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!