猴子選大王 C語言 雙向鏈表實現

來源:互聯網
上載者:User

 有M個猴子圍成一圈,每個有一個編號,編號從1到M。打算從中選出一個大王。經過協商,決定選大王的規則如下:從第一個開始,每隔N個,數到的猴子出圈,最後剩下來的就是大王。

要求:從鍵盤輸入M,N,編程計算哪一個編號的猴子成為大王。

實現如下:

 

#include <stdio.h>
#include <stdlib.h>

#define LEN sizeof(struct monkey)
struct monkey
{
 int num;
 struct monkey *next;
 struct monkey *prior;
};

void selcetKing(int m, int n)
{
 //建立帶頭結點的鏈表
 struct monkey *h, *p, *p1;
 
 p1=(struct monkey *)malloc(LEN);
 if(p1==NULL)
  printf("No enough memory!");
 
 p1->num=0;
 p1->next=NULL;
 p1->prior=NULL;
 
 h=p1;
 p=p1;
 
 for (int i=0; i<m; i++)
 {
  p1=(struct monkey *)malloc(LEN);
  if(p1==NULL)
   printf("No enough memory!");
  
  p1->num=i+1;
  p1->next=NULL;
  p1->prior=p;
  
  p->next=p1;
  p=p1;
 }

 h->num=m; //頭結點的資料域存放猴子的個數
 p->next=h->next;
 h->next->prior=p;
 
 //遍曆鏈表
 // printf("%d",h->num);
 // struct monkey *q=h->next;
 // for(int j=0; j<h->num; j++)//正向驗證
 // {
 //  printf("%d/n",q->num);
 //  q=q->next;
 // }
 
 // for(int r=0; r<h->num; r++) //反向驗證
 // {
 //  printf("%d/n",q->num);
 //  q=q->prior;
 // }
 
 struct monkey *q, *r, *s;
 q=r=s=h->next;
 while (h->num>1)
 {
  int j;
  for (j=1; j<n; j++)
  {
   q=q->next;
   r=r->next;
   s=s->next;
  }
  if (j==n)
  {
   q=q->prior;
   r=r->next;
   free(s);
   h->num--;
   
   if (h->num==1)
   {
    r->next=NULL;
    r->prior=NULL;
    q=r;
    s=r;
   }
   else
   {
    q->next=r;
    r->prior=q;
    s=r;
    q=r;
   }
  }
 }
 printf("%d/n",r->num);
}

void main()
{
 int m,n;
 printf("請輸入猴子數目及所報數目:");
 
 scanf("%d%d", &m, &n);
 
 if(m>0&&n>0)
  selcetKing(m,n);
 else
  printf("請輸入正整數!/n");
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.