|
| 1 | +// Java program to swap the nodes of a linked list rather |
| 2 | +// than swapping the data from the nodes. |
| 3 | +class Node { |
| 4 | + int data; |
| 5 | + Node next; |
| 6 | + |
| 7 | + Node(int data) { |
| 8 | + this.data = data; |
| 9 | + this.next = null; |
| 10 | + } |
| 11 | +} |
| 12 | + |
| 13 | +public class SwapNodes { |
| 14 | + |
| 15 | + // Function to swap nodes x and y in linked list by changing links |
| 16 | + static Node swapNodes(Node head, int x, int y) { |
| 17 | + |
| 18 | + // Nothing to do if x and y are the same |
| 19 | + if (x == y) { |
| 20 | + return head; |
| 21 | + } |
| 22 | + |
| 23 | + Node prevX = null, currX = null; |
| 24 | + Node prevY = null, currY = null; |
| 25 | + Node curr = head; |
| 26 | + |
| 27 | + // First loop to find x |
| 28 | + while (curr != null) { |
| 29 | + if (curr.data == x) { |
| 30 | + currX = curr; |
| 31 | + break; |
| 32 | + } |
| 33 | + prevX = curr; |
| 34 | + curr = curr.next; |
| 35 | + } |
| 36 | + |
| 37 | + curr = head; |
| 38 | + |
| 39 | + // Second loop to find y |
| 40 | + while (curr != null) { |
| 41 | + if (curr.data == y) { |
| 42 | + currY = curr; |
| 43 | + break; |
| 44 | + } |
| 45 | + prevY = curr; |
| 46 | + curr = curr.next; |
| 47 | + } |
| 48 | + |
| 49 | + // If either x or y is not present, nothing to do |
| 50 | + if (currX == null || currY == null) { |
| 51 | + return head; |
| 52 | + } |
| 53 | + |
| 54 | + // If x is not head of the linked list |
| 55 | + if (prevX != null) { |
| 56 | + prevX.next = currY; |
| 57 | + } else { |
| 58 | + head = currY; |
| 59 | + } |
| 60 | + |
| 61 | + // If y is not head of the linked list |
| 62 | + if (prevY != null) { |
| 63 | + prevY.next = currX; |
| 64 | + } else { |
| 65 | + head = currX; |
| 66 | + } |
| 67 | + |
| 68 | + // Swap next pointers |
| 69 | + Node temp = currY.next; |
| 70 | + currY.next = currX.next; |
| 71 | + currX.next = temp; |
| 72 | + |
| 73 | + return head; |
| 74 | + } |
| 75 | + |
| 76 | + static void printList(Node curr) { |
| 77 | + while (curr != null) { |
| 78 | + System.out.print(curr.data + " "); |
| 79 | + curr = curr.next; |
| 80 | + } |
| 81 | + System.out.println(); |
| 82 | + } |
| 83 | + |
| 84 | + public static void main(String[] args) { |
| 85 | + |
| 86 | + // Constructed linked list: 1->2->3->4->5 |
| 87 | + Node head = new Node(1); |
| 88 | + head.next = new Node(2); |
| 89 | + head.next.next = new Node(3); |
| 90 | + head.next.next.next = new Node(4); |
| 91 | + head.next.next.next.next = new Node(5); |
| 92 | + |
| 93 | + head = swapNodes(head, 4, 3); |
| 94 | + printList(head); |
| 95 | + } |
| 96 | +} |
0 commit comments