Data Structure problem in C: Josephus Circle(Taking elements manually) | Competitive coding



Data Structure problem in C: Josephus Circle(Taking elements manually) | Competitive coding:


In our programming website we teach computer coding to kids and pros for free online in easy way and gives knowledge about Data structure and alogorithm in C,Java,Python
 and other programming languages that may help you land an online job and make your programmers day successfull. 
We use best data structure notes and best programming resources. Here goes the article,dont forget to share with your friends 😃

Here we take elements manually of values that we want and  are inserted in a circle waiting to be executed.counting begins at a specified point in a circle and proceeds around the circle in a specified direction. After a specified number of elements skipped,the next element is executed. The procedure is repeated with the remaining elements,starting with the next element,going in the same direction and skipping the same number of element,untill only one element remains,and is freed.

The code is as follows:

#include"stdio.h"
#include"stdlib.h"
struct node 
{
int data;
struct node *next;
}*last=NULL;
struct node *q=NULL;
struct node *insert(int d)
{
struct node* p;
struct node *q;
p=(struct node*)malloc(sizeof(struct node));//allocating memory for the node to be inserted
p->data=d;
if(last==NULL) //when list is empty
{
last=p; 
p->next=last;
}
else
{
q=last; //point to the last(next of first)element
while(q->next!=last)
q=q->next; //traversing list
//adding new element
q->next=p; 
p->next=last;
}
return last;
}
void display(struct node *last)
{
struct node *q;
q=last;
while(q->next!=last)
{
printf("%d\t",q->data);
q=q->next;
}
printf("%d",q->data);
printf("\n");
}
int main()
{
int d,i,n,h,j;
struct node *p,*q;
printf("enter the number of item\n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("enter the node value\n");
scanf("%d",&d);
insert(d);
}
display(last);
printf("enter the no of node to be skiped\n");
scanf("%d",&h);
//logic of skip & execute
q=last;
while(q->next!=q)
{
for(j=1;j<h;j++)
{
q=q->next;//points to the h'th node
p=q->next; //point to the h+1'th node,i.e the node to be deleted
}
q->next=p->next;//the desired element is deleted
printf("%d will execute\n",p->data);//print the element which is executed
q=p->next;//now the element after the removed element becomes last and the process goes on
}
printf("\n%d will unchanged",q->data);
}


Post a Comment

0 Comments