无尽算法之 反转链表 (递归版)

反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

思路:

  1. 假设链表是[1, 2, 3, 4, 5]从最底层最后一个reverseList(5)来看
  2. 返回了5这个节点
  3. reverseList(4)中
  4. p为5
  5. head.next.next = head 相当于 5 -> 4
  6. 现在节点情况为 4 -> 5 -> 4
  7. head.next = null,切断4 -> 5 这一条,现在只有 5 -> 4
  8. 返回(return)p为5,5 -> 4
  9. 返回上一层reverseList(3)
  10. 处理完后返回的是4 -> 3
  11. 依次向上

题解:

/**
 * 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;
    }
}
发布了188 篇原创文章 · 获赞 323 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_33709508/article/details/104231146
今日推荐