LeetCode_206—— 反转链表

初级阶段,分析记录
方法一:递归实现( LeetCode 官方题解)
方法二:迭代实现

public class First_206 {
    /**
     * @description: 链表节点的内部类
     * @param:
     * @return:
     */
    public class ListNode {
        int val;
        ListNode next;

        ListNode(int val) {
            this.val = val;
        }
    }

    /**
     * @description: 利用递归实现
     * @param: head
     * @return: newHead
     */
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null)
            return head;
        ListNode newHead = reverseList(head.next);
        //注意 next 的含义,可以形象的理解成箭头的意思
        head.next.next = head;
        head.next = null;
        // newHead 应该一直是尾节点,不会变,最后作为新链表的头结点输出
        return newHead;
    }
}

递归问题就是一个隐式栈问题,通过手动 debug 方式逐行分析

以链表 2--->3--->4--->null 为例,输入为头结点 2 ,输出应该为新的头结点 4 
if()    return
p = re(2.next)
    p=re(3.next)
        if(4.next==null) return 4
    p=4
    4--->3
    3--->null
    return 4
p=4
3--->2
2--->null
return 4
public ListNode reverseList(ListNode head) {
        ListNode p = null;
        ListNode c = head;
        while (curr != null) {
            //临时保存下一个节点
            ListNode Temp = curr.next;
            //调整箭头的指向
            c.next = p;
            //依次往后挪动节点
            p = c;
            c = Temp;
        }
        return prev;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值