题目描述
解题思路
方法一:新建链表
一种比较清晰的解题思路就是新建一个空链表,然后不断的从原来那个单链表的头部摘下节点头插到新链表。
💥 复杂度分析
- 空间复杂度:空间复杂度 O(N)
- 时间复杂度:O(N)
package com.kami.leetcode.list_study;
import com.kami.leetcode.list_study.listNode.ListNode;
/**
* @Description: TODO
* @author: scott
* @date: 2021年12月13日 10:44
*/
public class Solution_206 {
public ListNode reverseList(ListNode head){
if(head == null || head.next == null){
return head;
}
// 新链表的虚拟头节点
ListNode newHead = new ListNode(0);
newHead.next = null;
// 直接用 head 指针遍历原链表, successor 记录当前 head 指向节点的后继节点
ListNode successor;
while (head != null){
successor = head.next;
// 不断的从原来那个单链表的头部摘下节点头插到新链表
head.next = newHead.next;
newHead.next = head;
// 进入下一个节点
head = successor;
}
return newHead.next;
}
}
方法二:原地反转
显然第一种方法对内存造成了一定的浪费,事实上,我们可以直接改变 next 的指向从而实现原地反转。
图像演示链接
💥 复杂度分析
- 空间复杂度:空间复杂度 O(1)
- 时间复杂度:O(N)
package com.kami.leetcode.list_study;
import com.kami.leetcode.list_study.listNode.ListNode;
/**
* @Description: TODO
* @author: scott
* @date: 2021年12月13日 10:44
*/
public class Solution_206 {
public ListNode reverseList(ListNode head){
/**
* 方法二:链表反转
*/
if(head == null || head.next == null){
return head;
}
ListNode pre = null;
ListNode cur = head;
while (cur != null){
ListNode tmp = cur.next;
cur.next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
}