美文网首页数据结构和算法
链表 - LeetCode 206.反转链表

链表 - LeetCode 206.反转链表

作者: 我阿郑 | 来源:发表于2023-11-01 11:55 被阅读0次

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

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

方法:迭代(双指针)

遍历链表,并在访问各节点时修改 next 引用指向

image.png

1、需要temp节点,存储cur.next
2、让cur.next 反过来指向pre
3、再让pre 和 cur 都向后移动一步

class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode cur = head, pre = null;
        while(cur != null) {
            ListNode tmp = cur.next; // 暂存后继节点 cur.next
            cur.next = pre;          // 修改 next 引用指向
            pre = cur;               // pre 暂存 cur
            cur = tmp;               // cur 访问下一节点
        }
        return pre;
    }
}

复杂度分析:
时间复杂度O(N) : 遍历链表使用线性大小时间。
空间复杂度O(1) : 变量 precur 使用常数大小额外空间。

相关文章

网友评论

    本文标题:链表 - LeetCode 206.反转链表

    本文链接:https://www.haomeiwen.com/subject/jnrvidtx.html