Swapping every pair of nodes in a single linked list

0

Provided n1->n2->n3->n4->n5
in general for each pair starting with n
have a temp variable that will keep copy of reference to n.next

Consider the link list n1->n2->n3->……

and n=n1
temp=n.next             //temp=n2
n.next=n.next.next//n1.next=n1.next.next=n3

temp.next=n          //n2.next=n1

Now move n to n.next//n=n1.next=n3
Repeat the same for next pair.but we have to link previous pair with the current pair
Which will have previous pairs 2nd element ? its temp.next
So make temp.next.next=n.next

Thats it!!

 

Also you can swap the pairs by just swapping the value.That is way too simple.Look at the 2nd function
Source code:

[gist https://gist.github.com/vishnujayvel/6049904]

Merge sort using recursion

0

#include<iostream>
using namespace std;

void merge(int A[],int temp[],int left,int mid,int right ){
int left_end=mid-1;
int temp_pos=left;
int size=right-left+1;
while((left<=left_end)&&(mid<=right)){
if(A[left]<=A[mid]){
temp[temp_pos++]=A[left++];
}
else{
temp[temp_pos++]=A[mid++];
}
}
while(left<=left_end)
temp[temp_pos++]=A[left++];

while(mid<=right)
temp[temp_pos++]=A[mid++];

for(int i=0;i<size;i++){
A[right–]=temp[right];
}
}
void mergesort(int A[],int temp[],int left,int right){
int mid=(left+right)/2;
if(left<right){
mergesort(A,temp,left,mid);
mergesort(A,temp,mid+1,right);
merge(A,temp,left,mid+1,right);

}

}
int main(){
int arr[]={0,45,67,988,99,100,111,1233,0};
int temp[9];
mergesort(arr,temp,0,8);
for(int i=0;i<9;i++)
cout<<arr[i]<<‘ ‘;
}