题目链接https://leetcode.cn/problems/reverse-linked-list/description/
必会题型——反转链表
我采用递归函数解法
方法一:新的头节点是全局变量
/**
* 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 {
//定义了一个全局变量,用记录最新的头节点
ListNode newhead;
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null){
newhead = head;
return head;
}
reverseList(head.next);
head.next.next = head;
head.next = null;
return newhead;
}
}
方法二:新的头节点是函数内的变量,且newhead一直指向的是最初的最后一个节点。
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode newhead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newhead;
}
}
供参考哦~学习共勉!!!