题目
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
解题思路
- 先排除特殊情况:当前链表包含节点数小于等于;
- 获取末尾节点,即反转后的头节点;
- 通过递归来反转节点间的上下级关系;
代码展示
class Solution {public ListNode reverseList(ListNode head) {if(head == null || head.next == null){return head;}ListNode temp = head;while (temp.next != null){temp = temp.next;}ListNode ans = temp;iterationNode(head, head.next);return ans;}public ListNode iterationNode(ListNode now, ListNode next){if(next.next == null){next.next = now;now.next = null;return now;}iterationNode(next, next.next).next = now;now.next = null;return now;}
}