Wednesday, August 31, 2011

Write a code to solve josephus problem in linked list.


//Write a code to solve josephus problem in linked list.
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
struct node
{
int data;
struct node *next;
};
main()
{
struct node *start=NULL;
int n;
void create(struct node **, int);
void josephus(struct node *);
printf("Enter the number of elements you want in your linked list :");
scanf("%d",&n);
create(&start,n);
josephus(start);
getch();  
}

void create(struct node **start,int n)
{
int i;
struct node *lst;
struct node *p;
lst=NULL;
for(i=1;i<=n;i++)
{
 p=(struct node *)malloc(sizeof(struct node));
 printf("Enter the %d element :",i);
 scanf("%d",&(p->data));
 if(*start==NULL)
    *start=p;
 else
   lst->next=p;
   lst=p;
   p->next=*start;
}
}


void josephus(struct node *start)
{
     struct node *temp,*p;
     int n,count;
     printf("\nwhich element you want to delete in josephus problem");
     scanf("%d",&n);
     while(start->next!=start)
     {
      count=1;
      p=start;
      while(count<=n-2)
      {
        p=p->next;
        count++;
      }
      temp=p->next;
      p->next=temp->next;
      free(temp);
      start=p->next;
      }
      printf("the last item in josephus problem is %d",start->data);
   
}

   

Previous Next Home
2 Comments
Comments

Mainu Bhi Sikha De Programming :D

hehe :)
koi n veer ,, tenu v krde a tyar...
:)

Leave a Comment

:)) ;)) ;;) :D ;) :p :(( :) :( :X =(( :-o :-/ :-* :| 8-} :)] ~x( :-t b-( :-L x( =))

Twitter Delicious Facebook Favorites More