Easy
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
0ms:
public ListNode swapPairs(ListNode head) {
if(head==null||head.next==null) return head;
ListNode root = new ListNode(0);
root.next = head;
ListNode node = root;
ListNode tmp = root.next;
while(tmp!=null&&tmp.next!=null){
node.next = tmp.next;
tmp.next = tmp.next.next;
node.next.next = tmp;
node = tmp;
tmp = node.next;
}
return root.next;
}
0ms:
public ListNode swapPairs(ListNode head) {
if(head==null||head.next==null) return head;
ListNode root = new ListNode(0);
root.next = head;
ListNode node = root;
ListNode tmp = root.next;
ListNode root2 = tmp.next;
while(tmp!=null&&tmp.next!=null){
node.next = tmp.next;
tmp.next = tmp.next.next;
node.next.next = tmp;
node = tmp;
tmp = node.next;
}
return root2;
}