Swap Nodes in Pairs of Linked List | Linked List Problem | LeetCode 24

4 years ago Lalit Bhagtani 0

Problem Statement

You have given a singly linked list, swap every two adjacent nodes and return the new head of the linked list.

Example 

Linked List

Input :- head = [5, 4, 10, 15, 1]
Output :- [4, 5, 15, 10, 1]
Input :- head = [5, 4, 10, 15, 1, 7]
Output :- [4, 5, 15, 10, 7, 1]

Solution

This problem can be solved in following steps :-

  1. Create two variables first, second. Initially assign first to first node of the linked list and second to second node of the linked list.
  2. Move both variables by one node, till both reaches the last node of the linked list.
  3. Assign next of second variable to the next of first variable.

Program

public class Main {

	public static void main(String[] args) {
		
		ListNode head = null;		
		ListNode node = new ListNode(5);
		head = node;		
		node.next = new ListNode(4);
		node = node.next;		
		node.next = new ListNode(10);
		node = node.next;		
		node.next = new ListNode(15);
		node = node.next;		
		node.next = new ListNode(1);
		node = node.next;		
		node.next = new ListNode(7);	
		
		Main main = new Main();
		head = main.swapPairs(head);
		while(head != null) {
			System.out.print(head.value + ", ");
			head = head.next;
		}
	}
	
	/* Solution */
	public ListNode swapPairs(ListNode head) {
        if(head != null && head.next != null){
            ListNode previous = null;
            ListNode first = head;        
            ListNode second = head.next;
        
            while(first != null && second != null){
                first.next = second.next;
                second.next = first;

                if(previous == null){
                    head = second;
                } else {
                    previous.next = second;
                }

                previous = first;
                first = first.next;
                if(first != null){
                    second = first.next;
                }                        
            }
        }    
        return head;        
    }
	
	/* Definition of Linked List Node */
	public static class ListNode {		
		int value;
		ListNode next;
		
		public ListNode(int value) {
			this.value = value;
		}		
	}
}

Result

4, 5, 15, 10, 7, 1, 

That’s all for Swap Nodes in Pairs of Linked List in Java, If you liked it, please share your thoughts in a comments section and share it with others too.