Pairwise swap elements of a linked list by swapping data
PROBLEM :
Given a singly linked list, write a function to swap elements pairwise. For example, if the linked list is 1->2->3->4->5 then the function should change it to 2->1->4->3->5, 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.
Input:
In this problem, method takes one argument: the head of the linked list. The function should not read any input from stdin/console.
The struct Node has a data part which stores the data and a next pointer which points to the next element of the linked list.
There are multiple test cases. For each test case, this method will be called individually.
Output:
Pairwise swap linked list elements .
Note: If you use "Test" or "Expected Output Button" use below example format
Example:
Input:
1
8
1 2 2 4 5 6 7 8
Output:
2 1 4 2 6 5 8 7
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
/*
Pairwise swap a linked list
The input list will have at least one element
node is defined as
struct node
{
int data;
struct node *next;
}
*/
void pairWiseSwap(struct node *head)
{
struct node *temp ;
int swap ;
temp=head ;
while(temp!=NULL&&temp->next!=NULL)
{
swap=temp->data ;
temp->data=temp->next->data ;
temp->next->data=swap ;
temp=temp->next->next ;
}
}
---------------------------------------------------------------------------------
Given a singly linked list, write a function to swap elements pairwise. For example, if the linked list is 1->2->3->4->5 then the function should change it to 2->1->4->3->5, 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.
Input:
In this problem, method takes one argument: the head of the linked list. The function should not read any input from stdin/console.
The struct Node has a data part which stores the data and a next pointer which points to the next element of the linked list.
There are multiple test cases. For each test case, this method will be called individually.
Output:
Pairwise swap linked list elements .
Note: If you use "Test" or "Expected Output Button" use below example format
Example:
Input:
1
8
1 2 2 4 5 6 7 8
Output:
2 1 4 2 6 5 8 7
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
/*
Pairwise swap a linked list
The input list will have at least one element
node is defined as
struct node
{
int data;
struct node *next;
}
*/
void pairWiseSwap(struct node *head)
{
struct node *temp ;
int swap ;
temp=head ;
while(temp!=NULL&&temp->next!=NULL)
{
swap=temp->data ;
temp->data=temp->next->data ;
temp->next->data=swap ;
temp=temp->next->next ;
}
}
---------------------------------------------------------------------------------
Comments
Post a Comment