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

• ``````public ListNode swapPairs(ListNode head) {
// If linked list is empty or there is only one node in list
}
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;
}
}
}
``````

• 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 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;
}

}

}
``````

• @shanks0892 Thanks for making it more clear :)

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