美文网首页
leetcode-206 反转链表 python3

leetcode-206 反转链表 python3

作者: _咚咚咚东 | 来源:发表于2020-03-02 10:19 被阅读0次

采用双指针法,时间复杂度O(n),空间复杂度O(1)

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        pre,cur = None,head #双指针
        while cur: #边界条件
            temp = cur.next #暂时存储cur.next节点,用于cur指针遍历
            cur.next = pre
            pre = cur
            cur = temp
        return pre #返回头部节点

相关文章

网友评论

      本文标题:leetcode-206 反转链表 python3

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