1. 程式人生 > >有N個人圍成一圈,順序排號。從第一個開始報數,(從1到3報數),凡報道3的人退出圈子,問最後留下的是原來第幾號那位

有N個人圍成一圈,順序排號。從第一個開始報數,(從1到3報數),凡報道3的人退出圈子,問最後留下的是原來第幾號那位

問題:

有n個人圍成一圈,按順序從1到n編好號。從第一個人開始報數,報到3的人退出圈子,下一個人從1開始報數,報到3的人退出圈子。如此下去,直到留下最後一個人。請按退出順序輸出退出圈子的人的編號

思路:

用資料結構中的迴圈連結串列解決此題

程式碼:

#include<stdio.h>
#include <stdlib.h>
typedef struct node {
    int num;
    struct node* next;
}Node,*PNode;
typedef struct point {
    PNode head;
    PNode tail;
}Point;
void init(Point* p) {
    p->head = (PNode)malloc(sizeof(Node));
    p->tail = p->head;
    printf
("input the num of people\n"); int pNum; scanf("%d", &pNum); for ( int i = 0; i < pNum; i++) { PNode tPoint= (PNode)malloc(sizeof(Node)); p->tail->next = tPoint; p->tail = tPoint; p->tail->num = i+1; } p->tail->next
= p->head->next; } int counting(Point* p) { int count = 0; PNode pNow = p->head; while(pNow->next != pNow){ pNow = pNow->next; count++; if (count==2) { PNode pTemp = pNow->next; pNow->next = pNow->next->next; free(pTemp); count = 1
; pNow = pNow->next; } } return pNow->num; } void print(Point* p) { //test PNode pNow = p->head; pNow = pNow->next; do{ printf("%d\n", pNow->num); pNow = pNow->next; }while (pNow->next != p->head->next); } int main() { Point p; init(&p); // print(&p); int count = counting(&p); printf("the last people is %dth", count); return 0; }

這裡寫圖片描述