LeetCode. 206.反转一个单链表(迭代&递归)

LeetCode.
206.反转一个单链表。

示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
Related Topics 链表

方法1:迭代
思路分析:

申请两个指针,第一个指针叫 pre,初始指向 null 。第二个指针 cur 指向 head,此处cur防止遍历时修改head的值。然后不断遍历 cur。每次迭代到 cur,用一个中间节点tem保存cur.nextcur.next指向pre,然后pre前进一位到之前cur的位置,cur前进一位到tem保存的下一个节点位置,cur 变成 null 即代表遍历结束。此时pre 就是最后一个节点。
借用力扣(LeetCode)的作者:wang_ni_ma的一个图,更容易看懂理解。在这里插入图片描述

具体代码:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        while(cur !=null){
            ListNode tem = cur.next;
            cur.next = pre;
            pre = cur;
            cur = tem;
        }
        return pre;

    }
}
方法2:递归
思路分析:

既然是递归,我们就需要知道他递归终止条件是什么。
对于这个题,终止条件很明显就是head == null || head.next == null
而且因为是递归,我们就不用考虑他前面具体怎么处理,经过ListNode cur = reverseList(head.next);处理后,我们只需要关心head和head.next节点怎么处理就可以了。我们假设head节点为a,head.next为b。
因为b要逆序,也就是重新指向a,即让b.next = a
但是这里要切记!此时的b.next指向a,同时a.next也因为正序没处理,还指向着b。也就是说,a和b成了一个环。因此,我们要断掉这个环,也就是使a.next=null

具体代码:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }
        ListNode cur = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return cur;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值