约霍夫问题 链表实现

 

#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
    int data;
    struct node *next;
} node;

node *create(int n)
{
    node *head,*tail,*pnew;
    head = (node*)malloc(sizeof(node));
    tail = head;
    int i=1;

    if( n != 0)
    {
        //将1到n节点连起来
        while(i <= n)
        {

            //创建新节点并且赋值
            pnew = (node*)malloc(sizeof(node));
            pnew->data = i++;

            //将前后节点连接起来
            tail->next = pnew;
            tail = pnew;
            // printf("%d\n ",i);
        }
        //将最后个节点和第一个节点连接起来形成一个环
        pnew->next = head->next;
    }

    free(head);


    return pnew->next;
}

int main()
{
    int n,m;
    printf("请输入n和m :\n");
    scanf("%d%d",&n,&m);
    int i;
    node *p = create(n);
    node *temp;

    m = n%m;
    printf("1111--%d\n",p->next->data);
   // printf("m = %d",m);

    //当p和自己不是同一个的时候进行循环
    while(p != p->next)
    {
        for(i= 1; i<m; i++)
        {
            p = p->next;
        }
        //printf("aaaaa%d->\n",p->data);
        printf("%d->",p->next->data);

        //temp指向被删除点的前驱
        temp = p->next;
        p->next = temp->next;
        free(temp);

        p = p->next;
    }

    //删除
    printf("%d->",p->data);
    return 0;
}

 

点赞