206. 反转链表
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
/**
* 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) return null;
if(head.next == null ) return head;
//递归到下一个节点
ListNode next = reverseList(head.next);
//回溯下一个节点指向当前节点(不能用递归返回的next,因为该next为尾结点,作为反转后的头结点)
head.next.next = head;
//当前节点指向指针清空,防止成环
head.next = null;
return next;
}
}