Insert in a circular sorted linklist

0
#include<iostream>
using namespace std;
struct node
{
int data;
struct node *next;
};
struct node* createNewNode(int data){
struct node* nn=new struct node();
nn->data=data;
nn->next=NULL;
return nn;
}
struct node* sortedInsert(node *head,int data){
struct node* newNode=createNewNode(data);
struct node* current=head;
if(current==NULL){//if the circular LL is empty
newNode->next=newNode;
head=newNode;
}
else if(current->data>=newNode->data){// if newNode has to be inserted before the head
while(current->next!=head){
current=current->next;
}
current->next=newNode;
newNode->next=head;
head=newNode;
}
else{//if the newNode has to be inserted somewhere inbetween the list
while(current->next!=head&&current->next->data<newNode->data)
current=current->next;
newNode->next=current->next;
current->next=newNode;
}
return head;
}
void printList(struct node *start)
{
struct node *temp;
if(start != NULL)
{
temp = start;
cout<<endl;
do {
cout<<temp->data<<" ";
temp = temp->next;
} while(temp != start);
}
}
int main()
{
struct node *head = NULL;
for(int i = 6; i>0; i--)
{
head=sortedInsert(head,i);
}
printList(head);
return 0;
}

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]