Given a linked list, swap every two adjacent nodes and return its head. Can some one help me, Memory Limit Exceeded


  • 0
    A
    public ListNode swapPairs(ListNode head) {
          // If linked list is empty or there is only one node in list
            if (head == null || head.next == null) {
                return head;
            }
    ListNode prev = head;
        ListNode curr = head.next;
        head = prev.next;
        while(curr != null){
            prev.next = curr.next.next;
            curr.next = prev;
            if(curr.next.next == null){
                prev.next = curr.next;
                break;
            }
            prev = prev.next;
            curr = curr.next;
        }
        return head;
    }
    }
    

  • 1
    S

    assume the linked list to be : 1 --> 2 --> 3 -->null
    then, according to your algorithm , prev =1 ; curr =2; head =2;

    while ( curr!=null)
    {
    prev.next == curr.next.next       // which is null
    
    }
    

    Check out my code which is somewhat similar to yours :

    public class Solution {
        public ListNode swapPairs(ListNode head) {
            
    		if (head !=null && head.next !=null)
    		{
    			
    		 swap(head,head.next);
    		}
    		return head;
    	}
    	
    	public void swap(ListNode prev, ListNode next1)
    	{
    		while ( prev != null && next1 !=null){
    		int tmp = prev.val;
    		prev.val = next1.val;
    		next1.val = tmp;
    		
    		if (next1.next != null)
    		{
    			prev = next1.next;
    			if(prev.next !=null)
    			{
    				next1 = prev.next;
    				
    			}
    			else break;
    			
    			
    		}
    		else break;
    		}
    		
    		
    		
    	}
            
            
            
        }
    

  • 0
    A

    @shanks0892 Thanks for making it more clear :)


Log in to reply
 

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