剑指offer 35 反转链表-java实现

剑指offer 35 反转链表-java实现,第1张

acwing 35 反转链表-java实现 原题链接

定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点。

思考题:

请同时实现迭代版本和递归版本。
数据范围
链表长度 [0,30]。

代码案例:输入:1->2->3->4->5->NULL
输出:5->4->3->2->1->NULL

题解

1、 迭代法

a b 两个指针 往下走
b的next指针 指向 a
a = b
因为这时候b.next =a 了 所以想让 b跑到第三个小球的那个位置上 就要提前
存上 b.next 也就是c

 /**
 * 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 n = cur.next ;
            cur.next = pre ;
            pre = cur ;
            cur = n ;
        }
        return pre ;
    }
}

2 递归 回溯法

递归的话 我们从第二个点开始的话 反转之后 要把第二个点的next也就是head.next.next 指向第一个头节点head 然后head.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 tail =  reverseList(head.next);
        head.next.next = head ;
        head.next = null ;
        return tail ;
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/923382.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-16
下一篇 2022-05-16

发表评论

登录后才能评论

评论列表(0条)

保存