Why was my code rejected by "exceed time limit"?


  • 0
    J

    public class Solution {
    public ListNode reverseList(ListNode head) {
    if(head==null || head.next==null)
    return head;
    ListNode pre=head;
    ListNode change=pre.next;
    ListNode next=pre.next.next;
    while(change !=null) {
    change.next=pre;
    pre=change;
    change=next;
    if (next!=null)
    next=next.next;
    }
    return pre;
    }
    }


  • 0
    Y
    This post is deleted!

  • 0
    E

    Let's take input 1->2->null as an example:

    after initialization, pre -> 1, change -> 2, next-> null,
    after "change.next = pre" you created a loop,( i.e 1<->2)
    after this pre = change, pre -> 2
    change = next, change-> null, after the first iteration, while loop ends and you return pre, so essentially you are returning a cycle list
    Let me know if this helps


  • 0
    J

    @Enkri_ Thanks a lot for your reply!


Log in to reply
 

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