题目

定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。

示例:

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

限制:

  • 0 <= 节点个数 <= 5000

来源:力扣(LeetCode)
链接:​​​https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof​

解题思路

解题思路有两种:迭代和递归

迭代:

  • 定义两个指针pre,cur
  • cur不为null时,执行迭代
  • 保存cur.next为临时变量,使得cur.next = pre
  • pre和cur指针后移
  • 返回pre

递归:

  • 递归结束条件:当前节点为null或者当前节点的next为null
  • 递归调用,返回结果为node
  • 当前节点的下一个节点next指向当前节点:head.next.next = head
  • 当前节点的next置空,head.next = null
  • 返回node

代码

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {

public ListNode reverseList(ListNode head) {
// 迭代
// 定义两个指针
ListNode pre = null;
ListNode cur = head;
// 当前节点不为null时迭代
while (cur != null) {
// 保存当前指针的next
ListNode next = cur.next;
// 当前指针的next指向pre
cur.next = pre;
// 指针后移
pre = cur;
cur = next;
}
// 注意,此时cur为null,所以这里返回的是pre
return pre;
}

public ListNode reverseList1(ListNode head) {
// 递归
// 递归结束条件:当前节点为null或者当前节点是尾节点
if (head == null || head.next == null) {
return head;
}

// 递归调用
ListNode node = reverseList(head.next);
// 当前节点的下一个节点的next指向当前节点
// 因为上面head.next已经判空了
head.next.next = head;
// 当前节点的next指向空
head.next = null;
// 返回尾节点
return node;
}
}

复杂度

迭代法:

  • 时间复杂度:O(n),n为链表的长度
  • 空间复杂度O(1),指针占用常数级空间

递归法:

  • 时间复杂度:O(n),n为链表的长度
  • 空间复杂度:O(n),递归调用占用n个额外空间