Pairwise Swap elements of LL

Implementation in C:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node* next;
};
void push(struct node** ref, int newData)
{
    struct node* newNode = (struct node*)malloc(sizeof(struct node));
    newNode->data = newData;
    newNode->next = (*ref);
    (*ref) = newNode;
}
void print(struct node* n)
{
    struct node* temp = n;
    if(temp == NULL)
    {
    printf("Empty LinkedList");
    }
    while(temp!=NULL)
    {
    printf(" %d",temp->data);
    temp=temp->next;
    }
}
void pairswap(struct node* head)
{
    struct node* current = head;
    while(current!=NULL && current->next != NULL)
    {
    swap(&current->data,&current->next->data);
    current = current->next->next;
    }
}
void swap(int* first,int* second)
{
    int* temp;
    temp = *first;
    *first = *second;
    *second = temp;
}
int main()
{
    struct node* head = NULL;
    push(&head,1);
    push(&head,2);
    push(&head,3);
    push(&head,4);
    push(&head,5);
    push(&head,6);
    push(&head,7);
    push(&head,8);
    print(head);
    pairswap(head);
    printf("\n");
    print(head);

}

Output:
8 7 6 5 4 3 2 1
7 8 5 6 3 4 1 2

Time Complexity:
O(n)

Comments

Popular posts from this blog

Three mislabeled Jar

Difference between Macro And function