来源

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-linked-list/

描述

反转一个单链表。

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

进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

题解

迭代

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. class Solution {
  10. public ListNode reverseList(ListNode head) {
  11. ListNode curr = head, prev = null;
  12. while (curr != null) {
  13. ListNode temp = curr.next;
  14. curr.next = prev;
  15. prev = curr;
  16. curr = temp;
  17. }
  18. return prev;
  19. }
  20. }

复杂度分析

  • 时间复杂度:206. 反转链表(Reverse Linked List) - 图1
  • 空间复杂度:206. 反转链表(Reverse Linked List) - 图2

递归

递归的经典算法,从后往前反转

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. class Solution {
  10. public ListNode reverseList(ListNode head) {
  11. if (head == null || head.next == null) {
  12. return head;
  13. }
  14. ListNode last = reverseList(head.next);
  15. head.next.next = head;
  16. head.next = null; // 切记此处
  17. return last;
  18. }
  19. }

复杂度分析

  • 时间复杂度:206. 反转链表(Reverse Linked List) - 图3
  • 空间复杂度:206. 反转链表(Reverse Linked List) - 图4