|
| 1 | +package com.antesh.dsa.linkedlist; |
| 2 | + |
| 3 | +/* |
| 4 | +* 24. Swap Nodes in Pairs |
| 5 | +* Given a linked list, swap every two adjacent nodes and return its head. |
| 6 | +* You must solve the problem without modifying the values in the list's |
| 7 | +* nodes (i.e., only nodes themselves may be changed.) |
| 8 | +* |
| 9 | +* Input: head = [1,2,3,4] |
| 10 | +* Output: [2,1,4,3] |
| 11 | +* |
| 12 | +* Input: head = [] |
| 13 | +* Output: [] |
| 14 | +* |
| 15 | +* Input: head = [1] |
| 16 | +* Output: [1] |
| 17 | +* */ |
| 18 | + |
| 19 | +import java.util.Objects; |
| 20 | + |
| 21 | +public class SwapNodesInPair { |
| 22 | + |
| 23 | + public static ListNode head; |
| 24 | + |
| 25 | + class ListNode { |
| 26 | + int data; |
| 27 | + ListNode next; |
| 28 | + |
| 29 | + public ListNode() { |
| 30 | + } |
| 31 | + |
| 32 | + public ListNode(int data) { |
| 33 | + this.data = data; |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + public ListNode insert(ListNode head, int data) { |
| 38 | + if (Objects.isNull(head)) { |
| 39 | + return new ListNode(data); |
| 40 | + } |
| 41 | + ListNode temp = new ListNode(data); |
| 42 | + ListNode ptr = head; |
| 43 | + |
| 44 | + while (ptr.next != null) { |
| 45 | + ptr = ptr.next; |
| 46 | + } |
| 47 | + ptr.next = temp; |
| 48 | + |
| 49 | + return head; |
| 50 | + } |
| 51 | + |
| 52 | + public ListNode swapPairs(ListNode head) { |
| 53 | + |
| 54 | + if (head == null || head.next == null) { |
| 55 | + return head; |
| 56 | + } |
| 57 | + |
| 58 | + ListNode current = head; |
| 59 | + ListNode dummy = new ListNode(); |
| 60 | + dummy.next = head; |
| 61 | + ListNode previous = dummy; |
| 62 | + |
| 63 | + while(current != null && current.next != null) { |
| 64 | + previous.next = current.next; |
| 65 | + current.next = previous.next.next; |
| 66 | + previous.next.next = current; |
| 67 | + previous = current; |
| 68 | + current = current.next; |
| 69 | + } |
| 70 | + return dummy.next; |
| 71 | + } |
| 72 | + |
| 73 | + public void print(ListNode head) { |
| 74 | + ListNode ptr = head; |
| 75 | + System.out.print("[ "); |
| 76 | + while (ptr != null) { |
| 77 | + System.out.print(ptr.data + " --> "); |
| 78 | + ptr = ptr.next; |
| 79 | + } |
| 80 | + System.out.print(" ]"); |
| 81 | + System.out.println(); |
| 82 | + } |
| 83 | + |
| 84 | + public static void main(String[] args) { |
| 85 | + SwapNodesInPair swap = new SwapNodesInPair(); |
| 86 | + |
| 87 | + head = swap.insert(head, 1); |
| 88 | + head = swap.insert(head, 2); |
| 89 | + head = swap.insert(head, 3); |
| 90 | + head = swap.insert(head, 4); |
| 91 | + |
| 92 | + swap.print(head); |
| 93 | + |
| 94 | + ListNode result = swap.swapPairs(head); |
| 95 | + |
| 96 | + swap.print(result); |
| 97 | + } |
| 98 | +} |
0 commit comments