Site icon

Reverse singly linked List in pairs in java (example / non-recursive)

Fig 1: Reverse singly linked list in pairs

Example – reverse singly linked list in pairs using java.

Reverse singly linked list in pairs (refer Fig 1)

Fig 2: Linked list after pairwise swap

Algorithm: reverse single linked list in pairs in java (non recursive)

Time complexity of algorithm is O (n).

Fig 3: Pairwise swap of nodes

Program – reverse single linked list in pairs using iterative algorithm in java.

1.) ReverseLinkedListInPair Class:

package org.learn.Question;

import org.learn.List.Node;

public class ReverseLinkedListInPair {

	public static Node reverseLinkedListInPair(Node head) {

		Node prev = head;
		Node newHead = head.next;
		Node temp = head.next;

		while (head != null && head.next != null) {
			
			prev.next = head.next;
			head.next = temp.next;
			temp.next = head;
			
			if (head.next != null) {
				prev = head;
				head = head.next;
				temp = head.next;
			}
		}

		return newHead;
	}

	public static void insert(Node head, int data) {

		while (head.next != null)
			head = head.next;
		head.next = new Node(data);
	}

	public static void print(Node head) {

		while (head != null) {
			System.out.printf("%d ", head.data);
			head = head.next;
		}

		System.out.println("");
	}
}

2.) DemoLinkedListInPairs Class:

package org.learn.Client;

import org.learn.List.Node;
import org.learn.Question.ReverseLinkedListInPair;

public class DemoLinkedListInPairs {
	
	public static void main(String[] args) {
		
		int[] data = { 10, 20, 30, 40, 50 };
		Node head = new Node(data[0]);
		
		for (int count = 1; count < data.length; count++) {
			ReverseLinkedListInPair.insert(head, data[count]);
		}
		
		System.out.printf("1. Single linked list is : ");
		ReverseLinkedListInPair.print(head);

		System.out.printf("2. Reverse single linked list in pairs : ");
		head = ReverseLinkedListInPair.reverseLinkedListInPair(head);
		ReverseLinkedListInPair.print(head);
	}
}

3.) Node Class:

package org.learn.List;

public class Node {
	public int data;
	public Node next;

	public Node(int num) {
		this.data = num;
		this.next = null;
	}
}

Output – reverse singly linked List in pairs in java (iterative)

1. Single linked list is : 10 20 30 40 50 
2. Reverse single linked list in pairs : 20 10 40 30 50 

Download Code – reverse linked List in pairs (non-recursive)

Exit mobile version