Friday, February 27, 2015

Swap Kth node from beginning with Kth node from end in a Linked List

#include <stdio.h>
#include <stdlib.h>
struct node
{
    int data;
    struct node *next;
};

void push(struct node ** head_ref, int new_data)
{
    struct node* new_node = (struct node*) malloc(sizeof(struct node));
    new_node->data  = new_data;
    new_node->next = (*head_ref);
    (*head_ref)  = new_node;
}



void printList(struct node *head)
{
    struct node *temp = head;
    while (temp != NULL)
    {
        printf("%d ", temp->data);
        temp = temp->next;
    }
    printf("\n");
}



void Fun(struct node **Node,int x,int y){
struct node *p=*Node;
struct node *q=*Node;
while(p->next->data!=x)
{
p=p->next;
}
while(q->next->data!=y)
{
q=q->next;
}
struct node *m=p->next;
struct node *r=p->next->next;
struct node *s=q->next->next;
p->next=q->next;
p->next->next=r;
q->next=m;
q->next->next=s;
 }



int main()
{
    int i;
     struct node *p = NULL;
     for (i = 8; i >= 1; i--){
       push(&p, i);
     }
     printf("Before Swapping 3 and 6   :");
     printList(p);
     Fun(&p,3,6);
     printf("\nAfter Swapping 3 and 6  :");
    printList(p);
     getchar();
     return 0;
}