面試訓練圓圈中最後剩下的數

來源:互聯網
上載者:User

這個不就是約瑟夫環的問題麼,迴圈鏈表一般可以解這種題。之前網上還看到過數學解法,直接就計算出來的。

這道題考試幾率很大,可以跑跑~

#include "stdio.h"typedef struct Node{int data;struct Node *next;}Lnode;int main(){    Lnode *p,*q,*head;int n=0;int i=0;int m=0;int count;scanf("%d",&n);p=(Lnode *)malloc(sizeof(Lnode));p->data=0;p->next = NULL;head =p;for(i=1;i<n;i++){q=(Lnode *)malloc(sizeof(Lnode));q->data=i;q->next=NULL;p->next =q;p=p->next;}p->next=head;scanf("%d",&m);count =1;while(head->next !=head){if(count == m){p->next=head->next;q=head;head=head->next;count=1;free(q);continue;}head=head->next;p=p->next;count++;}printf("%d",head->data);free(head);return 0;}

迴圈鏈表可以直接秒殺它,但是 while迴圈內部的處理 還是需要事前考慮清楚的。

看書中能拿到offer的解法,頓感壓力很大。

研究一下

看了下還是有時間再來吧,這個看懂要時間

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.