[GeeksForGeeks] Swap nodes in a single linked list by changing links
Given a singly linked list whose nodes contain an integer as their keys. All keys are distinct.
Swap the node that has key x with the node that has key y.
Nothing is done if either x or y does not exist in the given linked list.
Do this swap by changing node links, not by swaping key values.
Key notes:
1. Use dummy node to simply the case that either x or y is the head node.
2. if x and y are not adjacent, then there is 4 links that need to be changed;
if they are adjacent, then there is only 3 links that need to be changed;
As a result, these 2 cases should be handled separately.
1 class ListNode{ 2 int key; 3 ListNode next; 4 ListNode(int key){ 5 this.key = key; 6 this.next = null; 7 } 8 } 9 public class Solution { 10 public ListNode swapTwoNodesOfGivenKeys(ListNode head, int x, int y){ 11 if(head == null || head.next == null || x == y){ 12 return head; 13 } 14 ListNode dummy = new ListNode(0); 15 dummy.next = head; 16 17 ListNode prevX = null, X = null, prevY = null, Y = null; 18 ListNode prevNode = dummy, currNode = head; 19 boolean foundX = false, foundY = false; 20 21 while(currNode != null){ 22 if(currNode.key == x){ 23 prevX = prevNode; 24 X = currNode; 25 foundX = true; 26 } 27 else if(currNode.key == y){ 28 prevY = prevNode; 29 Y = currNode; 30 foundY = true; 31 } 32 if(foundX && foundY){ 33 break; 34 } 35 prevNode = currNode; 36 currNode = currNode.next; 37 } 38 if(!foundX || !foundY){ 39 return dummy.next; 40 } 41 if(X == prevY){ 42 prevX.next = Y; 43 X.next = Y.next; 44 Y.next = X; 45 } 46 else if(Y == prevX){ 47 prevY.next = X; 48 Y.next = X.next; 49 X.next = Y; 50 } 51 else{ 52 prevX.next = Y; 53 ListNode temp = Y.next; 54 Y.next = X.next; 55 X.next = temp; 56 prevY.next = X; 57 } 58 return dummy.next; 59 } 60 }