約瑟夫環----C鏈表實現

約瑟夫環----C鏈表實現在這裏插入圖片描述

#include<stdio.h>
#include<stdlib.h>
struct list{
  int data;
  struct list *next;
};
typedef struct list list_node;
int main(){
  int size,number,j=0;
  scanf("%d %d",&size,&number);
  list_node *head,*p,*q;
  head=(list_node*)malloc(sizeof(list_node));
  head->data=1;
  head->next=NULL; 
  p=head;
  
  for(int i=1;i<size;i++){
  	p->next=(list_node*)malloc(sizeof(list_node));
  	p=p->next;
  	p->data=i+1;
	}
	
	p->next=head;
	p=p->next;
	//printf("%d",p->data);
	while(p->next!=p){
		
		j++;
		q=p;
		p=p->next; 
		if(j==number-1){
			j=0;
			q->next=p->next;
			printf("%d ",p->data);
			free(p);
			p=q->next;
		}
	}
	if(p->next=p){
		printf("%d",p->data);
	}


}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章