Sunday, August 12, 2012

Pairwise swapping of nodes in a Linked List

//pairwise swapping of linkedlist nodes
//INPUT : 1->2->3->4->5->6->7->8->9->10
// OUTPUT : 2->1->4->3->6->5->8->7->10->9

#include<stdio.h>
#include<stdlib.h>

typedef struct node{
int data;
struct node *next;
}Node;

void pairwiseSwap(Node **headRef){
Node *current = *headRef;
Node *temp;
Node *prev = NULL;
while(current != NULL && current->next != NULL){
temp = current->next;
current->next = temp->next;
temp->next = current;
if(prev != NULL){
prev->next = temp;
}
if(current == *headRef){
*headRef = temp;
}
prev = current;
current = current->next;
}
}

Node* newNode(int data){
Node *n = (Node*)malloc(sizeof(Node));
n->data = data;
n->next = NULL;
return n;
}

void buildList(Node **headRef){
int i;
for(i=10;i>0;i--){
Node *n = newNode(i);
n->next = *headRef;
*headRef = n;
}
}

void freeMem(Node *head){
    Node *temp;
    while(head != NULL){
        temp = head;
        head = head->next;
        free(temp);
    }
}

void display(Node *head){
while(head->next != NULL){
printf("%d->",head->data);
head = head->next;
}
printf("%d\n",head->data);
}

void main(){
Node *head = NULL;
buildList(&head);
display(head);
pairwiseSwap(&head);
display(head);
freeMem(head);
}

No comments:

Post a Comment