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 }

 

转载于:https://www.cnblogs.com/charmingblog/p/5202580.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值