Everyone thinks of changing the world, but no one thinks of changing himself.
意为 每个人都想要改变世界,却没人想过要改变自己
问题描述
反转一个单链表。比如,输入: 1->2->3->4->5->NULL,输出: 5->4->3->2->1->NULL。
如下是链表节点的定义:
/**
* Java 定义
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
解法一 迭代
分析
通过迭代实现单链表反转,需要从第二个节点开始进行反转,当前节点的next指向前一个节点,需要注意的是,我们需要保存当前节点next的节点,不然会出现链表断开的问题。
代码
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null) {
return head;
}
ListNode pre = head;
ListNode cur = head.next;
pre.next = null;
while(cur != null) {
// 保存当前节点next的节点
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
解法二 递归
分析
通过递归实现单链表反转,需要从倒数第二个节点开始进行反转,依次向前,将后一个节点的 next 指向当前节点。注意每次反转后要将当前节点的 next。
public static ListNode reverseList(ListNode head) {
if(head == null || head.next == null) {
return head;
}else {
ListNode node = reverseList(head.next);
head.next.next = head;
head.next = null;
return node;
}
}
总结
从两种方式效率比较,迭代和递归的时间复杂度都为O(n), 迭代的空间复杂度为O(1), 而递归由于需要消耗栈空间,所以空间复杂度为O(1),而且递归也不容易理解,所以解决此题,迭代是更佳的选择。