206. Reverse Linked List【easy】

206. Reverse Linked List【easy】

Reverse a singly linked list.

Hint:

A linked list can be reversed either iteratively or recursively. Could you implement both?

 

解法一:

 1 class Solution {
 2 public:
 3     ListNode* reverseList(ListNode* head) {
 4         ListNode * pre = NULL;
 5         
 6         while (head != NULL) {
 7             ListNode * next = head->next;
 8             head->next = pre;
 9             pre = head;
10             head = next;
11         }
12         
13         return pre;
14     }
15 };

 

解法二:

 1 class Solution {
 2 public:   
 3     ListNode* reverseList(ListNode* head) {
 4         if (!head || !(head -> next)) return head;
 5         ListNode* node = reverseList(head -> next);
 6         head -> next -> next = head;
 7         head -> next = NULL;
 8         return node; 
 9     }
10 }; 

参考了@jianchao.li.fighter 的代码

The basic idea of this recursive solution is to reverse all the following nodes after head. Then we need to set head to be the final node in the reversed list. We simply set its next node in the original list (head -> next) to point to it and sets its next to be NULL.

 

解法三:

 1 public ListNode reverseList(ListNode head) {
 2     /* recursive solution */
 3     return reverseListInt(head, null);
 4 }
 5 
 6 private ListNode reverseListInt(ListNode head, ListNode newHead) {
 7     if (head == null)
 8         return newHead;
 9     ListNode next = head.next;
10     head.next = newHead;
11     return reverseListInt(next, head);
12 }

参考了@braydenCN 的代码

 

转载于:https://www.cnblogs.com/abc-begin/p/7667897.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值