【单向循环链表及约瑟夫环】

单向循环链表的相关操作

创建

LoopList LoopListCreate(void)
{
    LoopList h= (Node*)malloc(sizeof(LoopList));
    if (h== NULL) 
    {
        printf("内存申请失败\n");
        return NULL;
    }
    h->data = 0;
    h->next = h;
    return h;
}

头插法

int LoopListInsertHead(LoopList h, int data)
{
    LoopList temp;
    if ((temp = (Node*)malloc(sizeof(*temp))) == NULL) 
    {
        printf("内存申请失败\n");
        return -1;
    }
    temp->data = data;
    temp->next = h->next;
    h->next = temp;
    h->len++;
    return 0;
}

尾插法

int LoopListInsertTail(LoopList h,int data)
{
    LoopList temp=(Node*)malloc(sizeof(LoopList));
    if (temp== NULL) 
    {
        printf("内存申请失败\n");
        return -1;
    }
    temp->data = data;
    LoopList p = h;
    while (p->next != h) {
        p = p->next;
    }
    temp->next = p->next;
    p->next = temp;
    h->len++;
    return 0;
}

尾删法

int LoopList_Delete_Tali(LoopList h)
{
    LoopList p = h;
    while (p->next->next!=h)
    {
        p=p->next;
    }
    free(p->next);
    p->next=h;
    h->len--;
}

删除头结点

LoopList LoopListCutHead(LoopList h)
{
    LoopList temp, p = h;
    temp = h->next;
    while (p->next != h) {
        p = p->next;
    }
    p->next =temp;
        free(h);
        h = NULL;
    return temp;
}

打印去头结点后的链表

void LoopListShow_last(LoopList h)
{
    LoopList p = h;
    while (h->next != p) {
        printf("%-4d", h->data);
        h = h->next;
    }
    printf("%-4d\n",h->data);
}

删除节点后的节点

int Delete_pos(LoopList p)
{
    LoopList temp;
    temp=(LoopList)malloc(sizeof(Node));
    temp=p->next;
    p->next = temp->next;
    free(temp);
    temp=NULL;
}

按位查找

Node *GetElem(LoopList L, int i)
{
    Node *p = L->next;
    int j = 1;
    if (i == 0)
    {
        return L;
    }
    if (i < 1)
    {
        return NULL;
    }
    while (p ->next!= L && j < i)
    {
        p = p->next;
        j++;
    }
    return p;
}

约瑟夫环

void joseph(int n, int k, int m)
{
    LoopList L = LoopListCreate();
    LoopList p = L->next;
    int i = 1;
    for (i = 1; i <= n; i++)
    {
        LoopListInsertTail(L, i);
    }
    LoopList l = LoopListCutHead(L);
    LoopListShow_last(l);
    for (i = 0; i < k + m - 2; i++)//先找到第一个要删除的节点
    {
        p = p->next;
    }
    printf("%d ", p->next->data);
    Delete_pos(p);//删除节点
    while (p->next != p)//直到剩余最后一个节点
    {
        for (i = 1; i < m; i++)//隔位删除
        {
            p = p->next;
        }
        printf("%d ", p->next->data);
        Delete_pos(p);
    }
    printf("%d ", p->data);
}


版权声明:本文为a1379292747原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
THE END
< <上一篇
下一篇>>