Why my solution Time Limit Exceeded?(JAVA)


  • 0
    H
    public class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head == null || head.next == null) return head;
    	ListNode finalhead = null;
        ListNode a = head;
        ListNode f = head;
        ListNode e = head.next;
        while(f != null && e != null) {
            f.next = e.next;
            e.next = f;
            ListNode tmp;
            tmp = f;
            f = e;
            e = tmp;
            if(a != head) {
            	a.next = f;
            }
            if(finalhead == null)
            	finalhead = f;
            if(f.next == null)
                break;
            f = f.next.next;
            if(e.next == null || e.next.next == null)
            	break;
            	e = e.next.next;
    
            if(a == head) {
                a = f.next;
            }
            else {
                a = a.next.next;
            }
        }
        return finalhead;
    }
    

    }


Log in to reply
 

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