Three ways in Python


  • 3
    J

    Definition for singly-linked list.

    class ListNode(object):

    def init(self, x):

    self.val = x

    self.next = None

    class Solution(object):

    def reverseList_1(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head == None or head.next == None:
            return head
        dummyHead = ListNode(None)
        dummyHead.next = head
        prev = head
        cur = head.next
        while cur != None:
            ## init
            nex = cur.next
            ## reverse
            cur.next = dummyHead.next
            prev.next = nex
            dummyHead.next = cur
            ## move
            cur = nex
        return dummyHead.next
            
    def reverseList_2(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head == None:
            return head
        prev = None
        curr = head
        while curr != None:
            next = curr.next
            curr.next = prev
            prev = curr
            curr = next
        return prev
    
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        ## By recursion
        if head == None or head.next == None:
            return head
        h = self.reverseList(head.next)
        tail = head.next
        tail.next = head
        head.next = None
        return h

  • 0
    S

    For the first solution, I don't understand the meaning of prev = head and prev.next=nex.
    How do these two sentences help?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.