(最近複習數據結構)約瑟夫環

#include <iostream.h>
#include<stdio.h>
#include<stdlib.h>
typedef struct DNode
{
 int data;
 DNode *next;
}DNode;
DNode* init(int n ,int* array)
{
 int i=0;
 DNode* ptr=NULL;
 DNode* head=NULL;
 while(i<n)
 {
  DNode* p=(DNode*)malloc(sizeof(DNode));
  if(ptr==NULL)
  {
   ptr=p;
   head=p;
   ptr->next=NULL;
  }
  else
  {
   ptr->next=p;
   ptr=p;
  }
  p->data=array[i];
  i++;
 }
 ptr->next=head;

 return head;
}
void check(DNode* head)
{
 int m=5;
 int count=0;
 DNode* ptr=head;
 while(ptr->next!=ptr)
 {
  if(ptr->data==0)
  {
   ptr=ptr->next;
  }
  else
  {
   if(count+1==m)
   {
    DNode* temp;
    temp=ptr->next;
       m=temp->data;
    ptr->next=ptr->next->next;
    delete(temp);
    count=0;
   }
   else
   {
    count++;
   }
   ptr=ptr->next;
  }
 }
 cout<<ptr->data<<endl;
}
void main()
{
 int n=3;
 int num[]={3,1,7};
 check(init(n,num));
}

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