Time Limit Exceeded


  • 0
    L

    /**

    • Definition for singly-linked list.
    • public class ListNode {
    • int val;
      
    • ListNode next;
      
    • ListNode(int x) {
      
    •     val = x;
      
    •     next = null;
      
    • }
      
    • }
      */
      public class Solution {
      public ListNode insertionSortList(ListNode head) {
    	if(head==null||head.next==null)
    		return head;
    
    	ListNode headNode=head; 
    	ListNode currentNode=headNode.next;
    	ListNode nextNode = null;
    	ListNode prevNode=head;
    
    	while(currentNode!=null){
    		nextNode= currentNode.next;
    		if(headNode.val>currentNode.val){
    			headNode.next=currentNode.next;
    			currentNode.next=headNode;
    			headNode=currentNode;
    		}else{
    			ListNode cmpNode = headNode.next;
    			while(cmpNode!=null && currentNode.val>cmpNode.val){
    				cmpNode=cmpNode.next;
    			}
    			if(currentNode!=cmpNode){
    				currentNode.next=cmpNode.next;
    				cmpNode.next=currentNode;
    				prevNode.next=nextNode;
    			}
    
    		}
    
    
    		prevNode=currentNode;
    		currentNode=nextNode;
    
    	}
    	return headNode;
    
    }
    

    }


Log in to reply
 

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