Given a singly linked list, write a function to swap elements pairwise. For example, if the linked list is 1->2->3->4->5->6->7 then the function should change it to 2->1->4->3->6->5->7, and if the linked list is 1->2->3->4->5->6 then the function should change it to 2->1->4->3->6->5
This problem has been discussed here. The solution provided there swaps data of nodes. If data contains many fields, there will be many swap operations. So changing links is a better idea in general. Following is the implementation that changes links instead of swapping data.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
class node {
public :
int data;
node* next;
};
node* pairWiseSwap(node* head)
{
if (head == NULL || head->next == NULL)
return head;
node* prev = head;
node* curr = head->next;
head = curr;
while ( true ) {
node* next = curr->next;
curr->next = prev;
if (next == NULL || next->next == NULL) {
prev->next = next;
break ;
}
prev->next = next->next;
prev = next;
curr = prev->next;
}
return head;
}
void push(node** head_ref, int new_data)
{
node* new_node = new node();
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void printList(node* node)
{
while (node != NULL) {
cout << node->data << " " ;
node = node->next;
}
}
int main()
{
node* start = NULL;
push(&start, 7);
push(&start, 6);
push(&start, 5);
push(&start, 4);
push(&start, 3);
push(&start, 2);
push(&start, 1);
cout << "Linked list before "
<< "calling pairWiseSwap() " ;
printList(start);
start = pairWiseSwap(start);
cout << "\nLinked list after calling"
<< "pairWiseSwap() " ;
printList(start);
return 0;
}
|
C
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void pairWiseSwap( struct Node** head)
{
if (*head == NULL || (*head)->next == NULL)
return ;
struct Node* prev = *head;
struct Node* curr = (*head)->next;
*head = curr;
while ( true ) {
struct Node* next = curr->next;
curr->next = prev;
if (next == NULL || next->next == NULL) {
prev->next = next;
break ;
}
prev->next = next->next;
prev = next;
curr = prev->next;
}
}
void push( struct Node** head_ref, int new_data)
{
struct Node* new_node = ( struct Node*) malloc ( sizeof ( struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void printList( struct Node* node)
{
while (node != NULL) {
printf ( "%d " , node->data);
node = node->next;
}
}
int main()
{
struct Node* start = NULL;
push(&start, 7);
push(&start, 6);
push(&start, 5);
push(&start, 4);
push(&start, 3);
push(&start, 2);
push(&start, 1);
printf ( "\n Linked list before calling pairWiseSwap() " );
printList(start);
pairWiseSwap(&start);
printf ( "\n Linked list after calling pairWiseSwap() " );
printList(start);
getchar ();
return 0;
}
|
Java
class LinkedList {
static Node head;
static class Node {
int data;
Node next;
Node( int d)
{
data = d;
next = null ;
}
}
Node pairWiseSwap(Node node)
{
if (node == null || node.next == null ) {
return node;
}
Node prev = node;
Node curr = node.next;
node = curr;
while ( true ) {
Node next = curr.next;
curr.next = prev;
if (next == null || next.next == null ) {
prev.next = next;
break ;
}
prev.next = next.next;
prev = next;
curr = prev.next;
}
return node;
}
void printList(Node node)
{
while (node != null ) {
System.out.print(node.data + " " );
node = node.next;
}
}
public static void main(String[] args)
{
LinkedList list = new LinkedList();
list.head = new Node( 1 );
list.head.next = new Node( 2 );
list.head.next.next = new Node( 3 );
list.head.next.next.next = new Node( 4 );
list.head.next.next.next.next = new Node( 5 );
list.head.next.next.next.next.next = new Node( 6 );
list.head.next.next.next.next.next.next = new Node( 7 );
System.out.println( "Linked list before calling pairwiseSwap() " );
list.printList(head);
Node st = list.pairWiseSwap(head);
System.out.println( "" );
System.out.println( "Linked list after calling pairwiseSwap() " );
list.printList(st);
System.out.println( "" );
}
}
|
Python3
class Node:
def __init__( self , data):
self .data = data
self . next = None
class LinkedList:
def __init__( self ):
self .head = None
def addToList( self , data):
newNode = Node(data)
if self .head is None :
self .head = newNode
return
last = self .head
while last. next :
last = last. next
last. next = newNode
def __str__( self ):
linkedListStr = ""
temp = self .head
while temp:
linkedListStr = (linkedListStr +
str (temp.data) + " " )
temp = temp. next
return linkedListStr
def pairWiseSwap( self ):
if ( self .head is None or
self .head. next is None ):
return
prevNode = self .head
currNode = self .head. next
self .head = currNode
while True :
nextNode = currNode. next
currNode. next = prevNode
if nextNode. next is None :
prevNode. next = nextNode
break
prevNode. next = nextNode. next
prevNode = nextNode
currNode = prevNode. next
linkedList = LinkedList()
linkedList.addToList( 1 )
linkedList.addToList( 2 )
linkedList.addToList( 3 )
linkedList.addToList( 4 )
linkedList.addToList( 5 )
linkedList.addToList( 6 )
linkedList.addToList( 7 )
print ( "Linked list before calling"
"pairwiseSwap() " ,
linkedList)
linkedList.pairWiseSwap()
print ( "Linked list after calling "
"pairwiseSwap() " ,
linkedList)
|
C#
using System;
public class LinkedList {
Node head;
public class Node {
public int data;
public Node next;
public Node( int d)
{
data = d;
next = null ;
}
}
Node pairWiseSwap(Node node)
{
if (node == null || node.next == null ) {
return node;
}
Node prev = node;
Node curr = node.next;
node = curr;
while ( true ) {
Node next = curr.next;
curr.next = prev;
if (next == null || next.next == null ) {
prev.next = next;
break ;
}
prev.next = next.next;
prev = next;
curr = prev.next;
}
return node;
}
void printList(Node node)
{
while (node != null ) {
Console.Write(node.data + " " );
node = node.next;
}
}
public static void Main(String[] args)
{
LinkedList list = new LinkedList();
list.head = new Node(1);
list.head.next = new Node(2);
list.head.next.next = new Node(3);
list.head.next.next.next = new Node(4);
list.head.next.next.next.next = new Node(5);
list.head.next.next.next.next.next = new Node(6);
list.head.next.next.next.next.next.next = new Node(7);
Console.WriteLine( "Linked list before calling pairwiseSwap() " );
list.printList(list.head);
Node st = list.pairWiseSwap(list.head);
Console.WriteLine( "" );
Console.WriteLine( "Linked list after calling pairwiseSwap() " );
list.printList(st);
Console.WriteLine( "" );
}
}
|
Javascript
<script>
var head;
class Node {
constructor(val) {
this .data = val;
this .next = null ;
}
}
function pairWiseSwap(node) {
if (node == null || node.next == null ) {
return node;
}
var prev = node;
var curr = node.next;
node = curr;
while ( true ) {
var next = curr.next;
curr.next = prev;
if (next == null || next.next == null ) {
prev.next = next;
break ;
}
prev.next = next.next;
prev = next;
curr = prev.next;
}
return node;
}
function printList(node) {
while (node != null ) {
document.write(node.data + " " );
node = node.next;
}
}
head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(5);
head.next.next.next.next.next = new Node(6);
head.next.next.next.next.next.next = new Node(7);
document.write( "Linked list before calling pairwiseSwap() " );
printList(head);
var st = pairWiseSwap(head);
document.write( "<br/>" );
document.write( "Linked list after calling pairwiseSwap() " );
printList(st);
document.write( "" );
</script>
|
Output
Linked list before calling pairWiseSwap() 1 2 3 4 5 6 7
Linked list after callingpairWiseSwap() 2 1 4 3 6 5 7
Time Complexity: The time complexity of the above program is O(n) where n is the number of nodes in a given linked list. The while loop does a traversal of the given linked list.
Auxiliary Space: O(1) since using constant space to track prev and next
Following is the recursive implementation of the same approach. We change the first two nodes and recur for the remaining list. Thanks to geek and omer salem for suggesting this method.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
class node {
public :
int data;
node* next;
};
node* pairWiseSwap(node* head)
{
if (head == NULL || head->next == NULL)
return head;
node* remaining = head->next->next;
node* newhead = head->next;
head->next->next = head;
head->next = pairWiseSwap(remaining);
return newhead;
}
void push(node** head_ref, int new_data)
{
node* new_node = new node();
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void printList(node* node)
{
while (node != NULL) {
cout << node->data << " " ;
node = node->next;
}
}
int main()
{
node* start = NULL;
push(&start, 7);
push(&start, 6);
push(&start, 5);
push(&start, 4);
push(&start, 3);
push(&start, 2);
push(&start, 1);
cout << "Linked list before calling pairWiseSwap() " ;
printList(start);
start = pairWiseSwap(start);
cout << "\nLinked list after calling pairWiseSwap() " ;
printList(start);
return 0;
}
|
C
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node* next;
};
struct node* pairWiseSwap( struct node* head)
{
if (head == NULL || head->next == NULL)
return head;
struct node* remaining = head->next->next;
struct node* newhead = head->next;
head->next->next = head;
head->next = pairWiseSwap(remaining);
return newhead;
}
void push( struct node** head_ref, int new_data)
{
struct node* new_node = ( struct node*) malloc ( sizeof ( struct node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void printList( struct node* node)
{
while (node != NULL) {
printf ( "%d " , node->data);
node = node->next;
}
}
int main()
{
struct node* start = NULL;
push(&start, 7);
push(&start, 6);
push(&start, 5);
push(&start, 4);
push(&start, 3);
push(&start, 2);
push(&start, 1);
printf ( "\n Linked list before calling pairWiseSwap() " );
printList(start);
start = pairWiseSwap(start);
printf ( "\n Linked list after calling pairWiseSwap() " );
printList(start);
return 0;
}
|
Java
class LinkedList {
static Node head;
static class Node {
int data;
Node next;
Node( int d)
{
data = d;
next = null ;
}
}
Node pairWiseSwap(Node node)
{
if (node == null || node.next == null ) {
return node;
}
Node remaining = node.next.next;
Node newhead = node.next;
node.next.next = node;
node.next = pairWiseSwap(remaining);
return newhead;
}
void printList(Node node)
{
while (node != null ) {
System.out.print(node.data + " " );
node = node.next;
}
}
public static void main(String[] args)
{
LinkedList list = new LinkedList();
list.head = new Node( 1 );
list.head.next = new Node( 2 );
list.head.next.next = new Node( 3 );
list.head.next.next.next = new Node( 4 );
list.head.next.next.next.next = new Node( 5 );
list.head.next.next.next.next.next = new Node( 6 );
list.head.next.next.next.next.next.next = new Node( 7 );
System.out.println( "Linked list before calling pairwiseSwap() " );
list.printList(head);
head = list.pairWiseSwap(head);
System.out.println( "" );
System.out.println( "Linked list after calling pairwiseSwap() " );
list.printList(head);
System.out.println( "" );
}
}
|
Python3
class Node:
def __init__( self , data):
self .data = data
self . next = None
class LinkedList:
def __init__( self ):
self .head = None
def addToList( self , data):
newNode = Node(data)
if self .head is None :
self .head = newNode
return
last = self .head
while last. next :
last = last. next
last. next = newNode
def __str__( self ):
linkedListStr = ""
temp = self .head
while temp:
linkedListStr = (linkedListStr +
str (temp.data) + " " )
temp = temp. next
return linkedListStr
def pairWiseSwap( self , node):
if node is None or node. next is None :
return node
remaining = node. next . next
newHead = node. next
node. next . next = node
node. next = self .pairWiseSwap(remaining)
return newHead
linkedList = LinkedList()
linkedList.addToList( 1 )
linkedList.addToList( 2 )
linkedList.addToList( 3 )
linkedList.addToList( 4 )
linkedList.addToList( 5 )
linkedList.addToList( 6 )
linkedList.addToList( 7 )
print ( "Linked list before calling "
"pairwiseSwap() " , linkedList)
linkedList.head = linkedList.pairWiseSwap(
linkedList.head)
print ( "Linked list after calling "
"pairwiseSwap() " , linkedList)
|
C#
using System;
public class LinkedList {
Node head;
class Node {
public int data;
public Node next;
public Node( int d)
{
data = d;
next = null ;
}
}
Node pairWiseSwap(Node node)
{
if (node == null || node.next == null ) {
return node;
}
Node remaining = node.next.next;
Node newhead = node.next;
node.next.next = node;
node.next = pairWiseSwap(remaining);
return newhead;
}
void printList(Node node)
{
while (node != null ) {
Console.Write(node.data + " " );
node = node.next;
}
}
public static void Main()
{
LinkedList list = new LinkedList();
list.head = new Node(1);
list.head.next = new Node(2);
list.head.next.next = new Node(3);
list.head.next.next.next = new Node(4);
list.head.next.next.next.next = new Node(5);
list.head.next.next.next.next.next = new Node(6);
list.head.next.next.next.next.next.next = new Node(7);
Console.WriteLine( "Linked list before calling pairwiseSwap() " );
list.printList(list.head);
list.head = list.pairWiseSwap(list.head);
Console.WriteLine( "" );
Console.WriteLine( "Linked list after calling pairwiseSwap() " );
list.printList(list.head);
Console.WriteLine( "" );
}
}
|
Javascript
<script>
var head;
class Node {
constructor(val) {
this .data = val;
this .next = null ;
}
}
function pairWiseSwap(node) {
if (node == null || node.next == null ) {
return node;
}
var remaining = node.next.next;
var newhead = node.next;
node.next.next = node;
node.next = pairWiseSwap(remaining);
return newhead;
}
function printList(node) {
while (node != null ) {
document.write(node.data + " " );
node = node.next;
}
}
head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(5);
head.next.next.next.next.next = new Node(6);
head.next.next.next.next.next.next = new Node(7);
document.write( "Linked list before calling pairwiseSwap() " );
printList(head);
head = pairWiseSwap(head);
document.write( "<br/>" );
document.write( "Linked list after calling pairwiseSwap() " );
printList(head);
document.write( "" );
</script>
|
Output
Linked list before calling pairWiseSwap() 1 2 3 4 5 6 7
Linked list after calling pairWiseSwap() 2 1 4 3 6 5 7
Time Complexity: O(n)
Auxiliary Space: O(n)
Pairwise swap adjacent nodes of a linked list by changing pointers | Set 2
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
06 Feb, 2023
Like Article
Save Article