剑指offer 35 反转链表-java实现
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 ;
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)