循环链表例题

/*n个人想玩残酷的死亡游戏,游戏规则如下:  
n个人进行编号,分别从1到n,排成一个圈,
顺时针从1开始数到m,数到m的人被杀,剩下的人继续游戏,
活到最后的一个人是胜利者。 
请输出最后一个人的编号。
Input
输入n和m值。m>1。
Output
输出胜利者的编号。
Sample Input
5 3
Sample Output
4 */
#include <stdio.h>
#include <stdlib.h>
typedef struct lnode{
    int data;
    struct lnode* next;
} node,*linklist;
void initlist(linklist &l){
     linklist p=(linklist)malloc(sizeof(node));
     p->data=1;
     p->next=p;//此处可以控制循环链表
     l=p;
}
void InsertEnd(linklist &l,int e){//从末尾插入元素
    linklist p,q;
    p=(linklist)malloc(sizeof(node));
    p->data=e;
    q=l;
    while(q->next!=l){//此处判断扫到末尾的条件为!=l
        q=q->next;
    }
    p->next=q->next;
    q->next=p;
}
int main(){
    int n,m;
    while(scanf("%d%d",&n,&m)!=EOF){
    linklist l;
    int i,res;
    initlist(l);
    for(i=2; i<=n; i++){
        InsertEnd(l,i);
    }
    linklist p,q;//q是p的前驱节点
    p=l;
    q=l;
    int ans;
     while(1){
              if(p->next==p)
              break;
        for(int i=1;i<m;i++){
             q=p;
             p=p->next;
        }
        linklist tmp=p;
       // ans=p->data;
       // printf("---%d
",ans);
        q->next=p->next;
        p=p->next;
        free(tmp);
     }
           printf("%d
",p->data);
 //   Print(l);//输出表的元素
    }
    return 0;
}
/*
简洁代码
#include<stdio.h>
#include<stdlib.h>
struct node
{
    int data;
    struct node *next;
};
//删除操作
void Del(struct node *head, int m)
{
    struct node *p, *q;
    int i = 1; //计数。
    p = q = head;
    while(p != NULL)
    {
        if(i == m)
        {
//删除链表中元素。
            q->next = p->next;
            free(p);
            p = q->next;
            i = 1;
        }
        q = p;
        p = p->next;
        if(q == p)
        {
//最后一个元素,按照题意应该输出。
            printf("%d
", p->data);
            break;
        }
        i++;
    }
}
int main(){
    int n, m;
    while(scanf("%d %d", &n, &m) != EOF)
    {
        struct node *head = NULL;
        struct node *p, *q;
//创建循环链表。head为表头指针。
        p = (struct node *)malloc(sizeof(struct node));
        p->data = 1;
        head = p;
        for(int i = 2; i <= n; i++)
        {
            q = (struct node *)malloc(sizeof(struct node));
            q->data = i;
            p->next = q;
            p = q;
        }
        p->next = head;
//创建完毕。
        Del(head, m);
    }
    return 0;
}
*/
原文地址:https://www.cnblogs.com/13224ACMer/p/5034295.html