[LeetCode] 206. 反转链表
1. 问题描述
2. 实现思路
2.1 自己的思路
~~(一定要写出来啊喂)~
感觉好像快出来了,但是好像拼错了
// @lc code=start
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class Solution
{
public ListNode ReverseList(ListNode head)
{
if (head == null) return null;
if (head.next == null) return head;
else
{
var tail = ReverseList(head.next);
tail.next = head;
return tail;
}
}
}
// @lc code=end
2.2 题解思路
- 双指针法:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* temp; // 保存cur的下一个节点
ListNode* cur = head;
ListNode* pre = NULL;
while(cur) {
temp = cur->next; // 保存一下 cur的下一个节点,因为接下来要改变cur->next
cur->next = pre; // 翻转操作
// 更新pre 和 cur指针
pre = cur;
cur = temp;
}
return pre;
}
};
-
时间复杂度: O(n)
-
空间复杂度: O(1)
-
递归法:
class Solution {
public:
ListNode* reverse(ListNode* pre,ListNode* cur){
if(cur == NULL) return pre;
ListNode* temp = cur->next;
cur->next = pre;
// 可以和双指针法的代码进行对比,如下递归的写法,其实就是做了这两步
// pre = cur;
// cur = temp;
return reverse(cur,temp);
}
ListNode* reverseList(ListNode* head) {
// 和双指针法初始化是一样的逻辑
// ListNode* cur = head;
// ListNode* pre = NULL;
return reverse(NULL, head);
}
};
-
时间复杂度: O(n), 要递归处理链表的每个节点
-
空间复杂度: O(n), 递归调用了 n 层栈空间
-
递归的另一种
class Solution {
public:
ListNode* reverseList(ListNode* head) {
// 边缘条件判断
if(head == NULL) return NULL;
if (head->next == NULL) return head;
// 递归调用,翻转第二个节点开始往后的链表
ListNode *last = reverseList(head->next);
// 翻转头节点与第二个节点的指向
head->next->next = head;
// 此时的 head 节点为尾节点,next 需要指向 NULL
head->next = NULL;
return last;
}
};
- 时间复杂度: O(n)
- 空间复杂度: O(n)
2.3 优化(或者敲一遍题解?)
// @lc code=start
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class Solution
{
public ListNode ReverseList(ListNode head)
{
///用三指针,写的过程中能够弥补二指针在翻转过程中的想象
ListNode pre = null;
var move = head;
var next = head;
while (next != null)
{
next = next.next;
move.next = pre;
pre = move;
move = next;
}
head = pre;
return head;
}
}
// @lc code=end

浙公网安备 33010602011771号