数据结构教程 | 循环链表的实现及应用

Code Implementation and Application of Circular link list


1 Construction

1.1 Background

The Joseph ring problem: Given n persons (Numbers 1,2,3, … , n) sit around a round table and count clockwise from the person named k to the person named m. His next guy starts at 1 again, starts counting clockwise, and the guy who counts to m goes out again; The game continued, until there was only one person left at the round table.

The problem is definitely an application of circular link list, before solving the problem, we first construct the circular link list.

1.2 Construct a circular link list

typedef struct node{
    int number;
    struct node * next;
}person;

person * initLink(int n){
    person * head=(person*)malloc(sizeof(person));
    head->number=1;
    head->next=NULL;
    person * cyclic=head;
    for (int i=2; i<=n; i++) {
        person * body=(person*)malloc(sizeof(person));
        body->number=i;
        body->next=NULL; 
        cyclic->next=body;
        cyclic=cyclic->next;
    }
    cyclic->next=head;			//End to end
    return head;
}

We can see the only difference from primary link list is that it links end to end, achieving by: cyclic->next=head

2 Solve the problem

void findAndKillK(person * head,int k,int m){
    person * tail=head;
    while (tail->next!=head) {	// Find the node for deletion
        tail=tail->next;
    }
    person * p=head;
    while (p->number!=k) {		// Find the person with number k
        tail=p;
        p=p->next;
    }
    while (p->next!=p) {		// Only when p->next==p could we know there's one man left
        for (int i=1; i<m; i++) {
            tail=p;
            p=p->next;
        }
        tail->next=p->next;		// Put down 'p'
        printf("Dequeued person's number:%d\n",p->number);
        free(p);
        p=tail->next;			// Continue
    }
    printf("Dequeued person's number:%d\n",p->number);
    free(p);
}

int main() {
    printf("The total number n?");
    int n;
    scanf("%d",&n);
    person * head=initLink(n);
    printf("Start from the number k?",n);
    int k;
    scanf("%d",&k);
    printf("The dequene number m?");
    int m;
    scanf("%d",&m);
    findAndKillK(head, k, m);
    return 0;
}

We assume that there are 6 people in the game, and we start from 4, the person who count to 3 will out and the game continue from next person.
Here’s the output:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值