反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
思路:
- 假设链表是
[1, 2, 3, 4, 5]
从最底层最后一个reverseList(5)来看 - 返回了5这个节点
- reverseList(4)中
- p为5
- head.next.next = head 相当于 5 -> 4
- 现在节点情况为 4 -> 5 -> 4
- head.next = null,切断4 -> 5 这一条,现在只有 5 -> 4
- 返回(return)p为5,5 -> 4
- 返回上一层reverseList(3)
- 处理完后返回的是4 -> 3
- 依次向上
题解:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null || head.next==null) return head;
ListNode p = reverseList(head.next);
head.next.next = head;
head.next=null;
return p;
}
}