美文网首页
Reverse Linked List (iterative)

Reverse Linked List (iterative)

作者: GakkiLove | 来源:发表于2020-01-19 08:15 被阅读0次

    Reverse a singly-linked list iteratively.

    Examples

    L = null, return null
    L = 1 -> null, return 1 -> null
    L = 1 -> 2 -> 3 -> null, return 3 -> 2 -> 1 -> null

    class Solution(object):
      def reverse(self, head):
        if not head:
          return None
        p = head
        q = head.next
        while q:
          head.next = q.next
          q.next = p
          p = q
          q = head.next
        return p
    

    相关文章

      网友评论

          本文标题:Reverse Linked List (iterative)

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