雙向約瑟夫環連結串列實現
阿新 • • 發佈:2018-12-11
#include<stdio.h> #include<stdlib.h> const int N = 1000; int m, n, k; struct people { int id; people *last, *next; }head; void creat(people *head) { people *p, *q, *end; p = (people*)malloc(sizeof(people)); p->id = n; head->next = p; p->next = head; p->last = head; end = p; for(int i = n - 1; i >= 1; i--) { q = p; p = (people*)malloc(sizeof(people)); p->next = q; head->next = p; q->last = p; p->id = i; } end->next = p; p->last = end; } void dele1(people *p, people *q) { people *pq; pq = p->next; q->next = p->next; pq->last = q; free(p); } void dele2(people *a, people *b) { people *pq; pq = a->last; b->last = a->last; pq->next = b; free(a); } int main() { int i, j; while(~scanf("%d%*c%d%*c%d", &n, &k, &m)) { if (n < 1 || k < 1 || m < 1) { printf("n,m,k must bigger than 0.\n"); continue; } if (k > n) { printf("k should not bigger than n.\n"); continue; } creat(&head); people *p, *q, *a, *b; p = head.next; while(p->id != k) p = p->next; a = p; for(i = 1; (p->id <= n && p->id >= 1) && (a->id <= n && a->id >= 1); i++) { q = p; for(j = 1; j < m; j++) { q = p; p = p->next; } b = a; for(j = 1; j < m; j++) { b = a; a = a->last; } if (a == p) { printf("%d,", p->id); people *pq = p->last; a = pq; pq = p->next; dele1(p, q); p = pq; } else { printf("%d-", p->id); printf("%d,", a->id); people *pq = p->next; int flag = 0; if (p == b) b = p->next; people *tem = p; dele1(p, q); p = pq; pq = a->last; if (p == a) p = b; dele2(a, b); a = pq; } } printf("\n"); } return 0; }