Why my python code TLE?


  • 0
    Y
    def reverseList(self, head):
        if head==None or head.next==None:
            return head
        pre=None
        current=head
        pnext=head.next
        while pnext != None:
            pre=current
            current = pnext
            pnext=pnext.next
            current.next=pre
        return current

  • 0
    Y

    The LinkList is a cycle in the final


  • 1
    X

    I met the same issue...I think you have to point the initial head to NULL so it because a singly list. Otherwise the list has a circle.
    i.e. you do "current.next=pre" first in the while loop


  • 0
    A
    # Definition for singly-linked list.
    

    class ListNode:

    def init(self, x):

    self.val = x

    self.next = None

    class Solution:
    # @param {ListNode} head
    # @return {ListNode}
    def reverseList(self, head):
    if head is None or head.next is None:
    return head
    pre = None
    cur = head
    h =head
    while cur:
    h = cur
    tmp = cur.next
    cur.next = pre
    pre = cur
    cur = tmp
    return h


Log in to reply
 

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