LeetCode_206

题意以及限制条件

  1. 题目LeetCode_206-1

  2. 限制条件:A linked list can be reversed either iteratively or recursively. Could you implement both?

想到的所有可能解法

  • Ways_1——迭代法:双指针

    1. 时间复杂度——O(n);空间复杂度——O(1);
    2. newNode:用来转置链表中结点的next域指向以及指向所有转置完成后的第一个结点;
    3. next:用于移动head指针,直到head == null;
    4. 核心思想——每次翻转两个节点,直到最后一个结点。
  • Ways_2——递归1

    1. 时间复杂度——O(n);空间复杂度——O(n);
    2. Ps: (head == null)-针对的是:空链表的输入;(head.next == null)-针对的是:大多数正常链表的输入情况;
    3. 核心思想——把整个链表看成“头节点+不包含头节点部分”所组成的:头节点部分的操作为Current Logic;其余部分的操作则为Drill Down。
  • Ways_3——递归2

    1. 时间复杂度——O(n);空间复杂度——O(n);
    2. 核心思想——每次翻转两个节点,直到最后一个结点。

对应的代码

  • Ways_1
class Solution {
    public ListNode reverseList(ListNode head) {

        ListNode newNode = null;
        while (head != null) {
            ListNode next = head.next;
            head.next = newNode;
            newNode = head;
            head = next;
        }
        return newNode;

    }
}
  • Ways_2
class Solution {
    public ListNode reverseList(ListNode head) {

        //Terminator
        if (head == null || head.next == null) 
            return head;
        //Drill Down
        ListNode newNode = reverseList(head.next);
        //Current Logic
        //head的下一个结点的next域指向head
        head.next.next = head;
        head.next = null;
        return newNode;
        //Restore Current Data

    }
}
  • Ways_3
class Solution {
    public ListNode reverseList(ListNode head) {

       return reverse(head, null);

    }

    public static ListNode reverse(ListNode head, ListNode newNode) {
        //Terminator
        if (head == null) 
            return newNode;
        //Current Logic
        ListNode next = head.next;
        head.next = newNode;
        //Drill Down
        return reverse(next, head);
        //Restore Current Data
    }

}

测试样例

LeetCode_206-2

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值