Swap kth node
PROBLEM :
Given an array, swap kth element from beginning with kth element from end.
Input:
The first line of input contains an integer T denoting the number of test cases.
The first line of each test case is N and k,N is the size of array and kth number.
The second line of each test case contains N input C[i].
Output:
Print the modified array.
Constraints:
1 = T = 100
1 = K = N = 500
1 = C[i] = 1000
Example:
Input
1
8 3
1 2 3 4 5 6 7 8
Output
1 2 6 4 5 3 7 8
---------------------------------------------------------------------------------
Simple C++ implementation :
---------------------------------------------------------------------------------
#include<iostream>
using namespace std;
void swap(int[],int,int) ;
int main()
{
int a[1000],t,no,i,k ;
cin>>t ;
while(t--)
{
cin>>no>>k ;
for(i=0;i<no;i++)
cin>>a[i] ;
swap(a,no,k) ;
for(i=0;i<no;i++)
cout<<a[i]<<" " ;
cout<<endl ;
}
return 0;
}
void swap(int a[],int no,int k)
{
int i,j,temp ;
i=0;j=no-1 ;
k-- ;
while(k--)
{
i++ ;
j-- ;
}
temp=a[i] ;
a[i]=a[j] ;
a[j]=temp ;
}
--------------------------------------------------------------------------------
Given an array, swap kth element from beginning with kth element from end.
Input:
The first line of input contains an integer T denoting the number of test cases.
The first line of each test case is N and k,N is the size of array and kth number.
The second line of each test case contains N input C[i].
Output:
Print the modified array.
Constraints:
1 = T = 100
1 = K = N = 500
1 = C[i] = 1000
Example:
Input
1
8 3
1 2 3 4 5 6 7 8
Output
1 2 6 4 5 3 7 8
---------------------------------------------------------------------------------
Simple C++ implementation :
---------------------------------------------------------------------------------
#include<iostream>
using namespace std;
void swap(int[],int,int) ;
int main()
{
int a[1000],t,no,i,k ;
cin>>t ;
while(t--)
{
cin>>no>>k ;
for(i=0;i<no;i++)
cin>>a[i] ;
swap(a,no,k) ;
for(i=0;i<no;i++)
cout<<a[i]<<" " ;
cout<<endl ;
}
return 0;
}
void swap(int a[],int no,int k)
{
int i,j,temp ;
i=0;j=no-1 ;
k-- ;
while(k--)
{
i++ ;
j-- ;
}
temp=a[i] ;
a[i]=a[j] ;
a[j]=temp ;
}
--------------------------------------------------------------------------------
Comments
Post a Comment