top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

DS: What a C program to swap the nodes of k th level ?

+4 votes
279 views

Please provide efficient C code by which nodes of the k-th level can be swapped.

posted Jan 18, 2017 by Neelam

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes
#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;
}
answer Feb 15, 2017 by Shivaranjini
...