DS-004 30 数据结构:循环链表的实现及应用

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:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Tinky2013/article/details/87281113