Problem Statement

Pattern:


Solution

void swap(ListNode pa, ListNode pb){
	// swap parents
	ListNode a = pa.next, b = pb.next;
	pa.next = b;
	pb.next = a;
	// swap children
	ListNode temp = a.next;
	a.next = b.next;
	b.next = temp;
}
 
public ListNode swapNodes (ListNode head, int k){
	ListNode dummy = new ListNode(-1), pa = dummy, pb = dummy, a = head, b = head;
	dummy.next = head;
 
	// find parent-a
	int count = 0;
	while(++count < k) {
		pa = pa.next;
		a = a.next;
	}
	// find parent-b
	while(a.next!= null) {
		a = a.next;
		pb = pb.next;
		b = b.next;
	}
	// swap nodes by their parents
	swap(pa, pb);
	return dummy.next;
}

Notes