0
点赞
收藏
分享

微信扫一扫

LeetCode 图解 | 206.反转链表


LeetCode 图解 |  206.反转链表_读研

下面开始今天的学习~

LeetCode 图解 |  206.反转链表_读研_02

今天分享的题目来源于 LeetCode 上第 206 号问题:反转链表。这道题目经常出现在算法面试中的笔试环节。

题目描述

反转一个单链表。

示例:

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

题目解析

在原链表之前建立一个空的节点 pre,然后从头节点 cur 开始,先保存 ​​cur->next​​ 为 next ,将 cur 的 next 节点变为 pre,pre 移到 cur,cur 移动到 next。

重复此操作直到 cur 成为末节点为止。

动画理解

参考代码

/**
* 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 cur = head, pre = null;
while (cur != null) {
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}

复杂度分析

  • 时间复杂度:O(n)。
  • 空间复杂度:O(1)。

相关题目推荐

  • LeetCode 26:删除排序数组中的重复项
  • LeetCode 203:移除链表元素

END


LeetCode 图解 |  206.反转链表_读研_03





举报

相关推荐

0 条评论