今天刷LeetCode刷到一道经典的链表题——反转链表(据说很多大厂面试考了这个)
题意如下,一句话概括就是把1->2->3->4->5 反转变成5->4->3->2->1:
这是题目给的代码,我们需要填空reverseList方法,代码在这里面写:
递归求解
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
* 这里注释掉的地方表示题目的提示,题目已经给出了定义的结点类,我们直接用就好
*/
class Solution {
public static ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode result = reverseList(head.next);
head.next.next=head;
head.next=null;
return result;
}
}
逐行来看: 我们以把 “ 1 2 3 4 5” 变成 “5 4 3 2 1 ” 为例
第一行, if (head == null || head.next == null)
当head为null时直接返回head;当head.next为空时,即遍历到“5”这个数,此时5的后面显然为空,head.next=null表示的就是遍历到了最后一个
第二行,我们定义了一个result,result=reverseList(head.next)是什么意思呢?
我们把例子代入,首先head是1,不满足if判断,直接到result = reverseList(head.next);
head.next是2,把2代入进reverseList进行判断,逐行运行,显然2不为空,第一行if判断不成立,走到这行代码(ListNode result = reverseList(head.next);)head.next=3,
把3代到reverseList进行判断,同样if判断不成立,此时head.next=4,
把4代到reverseList进行判断,又跑一遍函数if, 不成立,再代入
5 if成立(因为5的后一个为空 head.next=null),终于可以返回head,此时result = reverseList(head.next),result被赋值为5,result = reverseList(head.next)这一行代码终于执行完毕!我们终于可以执行下面的代码啦!
( 一遇到(ListNode result = reverseList(head.next);)就会先执行等号右边的内容,只有知道右边是什么才可以把它赋值给左边。但是问题在于等号右边并不能马上执行完,我们必须执行到最后一个数 有了return的结果才可以把它返回到reverseList,这时候右边才有具体的值。)
接下来的代码是:
head.next.next=head;
head.next=null;
由前面已知,此时head=4,
我们需要做的是把5指向4 ( head.next.next=head)
再把4指向5的指针消掉 (head.next=null)
最后返回result
测试结果如下:
如果还不清楚的话可以看看这个up的视频(因为我也是看她的才看明白的hhh,讲得很清楚)非常非常感谢up主!!