C语言约瑟夫环链表

#include <stdio.h>
#include <windows.h>
#include <string.h>
struct link * creat1(int n);
void out(struct link * head);
void free_(struct link * head);
struct link * jsf(struct link * head,int m);


struct link
{
int data;
struct link * next;
};


void main()
{
    struct link * head;
struct link * p;
int n,m;
printf("input n , m:");  //读入个数与约定删除数
scanf("%d %d",&n,&m);
head = creat1(n);
out(head);
p = jsf(head,m);
printf("\nlast: %d \n",p->data);
free(p);


}


struct link * jsf(struct link * head,int m)
{
    int i;
struct link * p = malloc(sizeof(struct link ));    //给无头结点链表添加辅助头结点,但循环链表的尾巴仍指向第一个元素点,而不是头结点
    struct link * q;
p->next = head;
head = p;
while(p->next != p) //只剩下一个节点时,即为结果
{
for(i = 0; i < m; i++)  //数到M删除一次
{
q = p;
p = p->next;
}
q->next = p->next;
free(p);
p = q;
}
free(head);//删除头结点
    return p;
}


struct link * creat1(int n)    //创建循环链表
{
    struct link * head;
    struct link * p;
struct link * q;
    int i = 1;
head = (struct link *)malloc(sizeof(struct link));
p = q = (struct link *)malloc(sizeof(struct link));
    p->data = i;
head->next=p;
while (i < n)
{
i++;
p = (struct link *)malloc(sizeof(struct link));
p->data = i;
q->next = p;
q = p;
}
p = head->next;   //删除头结点。使之为无头结点链表,多此一举,懒得改
    q->next = p;
free(head);
return p;
}


void out(struct link * head)  //输出无头结点链表
{
    struct link * p = head->next;
    printf("%d ",head->data);
while(p != head)
{
printf("%d ",p->data);
p = p->next;
}
putchar(10);
}


void free_(struct link * head)   //删除无头结点链表,未使用
{
    struct link * p = head->next;
struct link * q = head;
while(head != p)
{
q = p->next;
        free(p);
p = q;
}
    free(head);
}
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值