使用递归
/*** 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 ListNode reverseList(ListNode head) {//递归终止条件:链表为空或仅仅包含一个节点if(head == null || head.next == null) {return head; //这里返回的是head而不是null}//递归反转除当前节点之外的子链表ListNode newHead = reverseList(head.next);//此时子链表已经被反转,此时head.next是子链表反转后的末尾节点,我们需要将当前节点head添加到head.next之后head.next.next = head;//此时head所指的节点是反转后的末尾节点,需要切断尾巴head.next = null;return newHead;}
}