Why the code I change is time limit exceeded


  • 0
    N

    I just change the pivot.next=pivot.next.next ==> pivot=pivot.next

    why become time limit exceeded when i do the change

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
       public ListNode reverseList(ListNode head){
        if(head==null||head.next==null){
            return head;
        }
        ListNode pivot = head;
        ListNode frontier = head;
        while(pivot.next!=null){
            frontier = pivot.next;
            pivot = pivot.next;
            frontier.next = head;
            head = frontier;
        }
        return head;
    }
    }

  • 0
    K

    Hi, man.
    Say first object in linked list is A, second object is B. After first iteration. B.next points to A ,and A. next still points to B. which means pivot.next is head, head.next is pivot. Loop condition always true


Log in to reply
 

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