循环链表(快慢指针)—约瑟夫环

题目描述

以前也处理过一个约瑟夫环问题。
但是以前处理那个比较简单。它的m是固定的
这次m删除一次结点后要变化。所以卡了很久
通过这个题,感觉自己调试程序的能力有所增强
fighting

#include<stdio.h>
#include<stdlib.h>
typedef struct Node {
 int id;
 int password;
 struct Node *next;
}Node;
Node *Create_Tail() {
 printf("请输入初始人数: \n");
 int m;
 scanf("%d", &m);
 Node *Head = NULL, *pNew = NULL, *r = NULL;
 int passWord;
 int ID = 1;
 int count = 1;
 printf("请输入第1个人的密码:\n");
 scanf("%d", &passWord);
 while (1) {
  pNew = (Node *)malloc(sizeof(Node));
  pNew->id = ID++;
  pNew->password = passWord;
  if (Head == NULL) {
   Head = pNew;
   r = pNew;
  } else {
   r->next = pNew;
   r = pNew;
  }
  if (m == 1) {
   break;
  }
  printf("请输入第%d个人的密码:\n", ++count);
  scanf("%d", &passWord);
  m--;
 }
 r->next = Head;
 return r;
}
void Output(Node *r) {
 Node *LA;
 LA = r->next;
 printf("编号:%d密码:%d\n", LA->id, LA->password);
 LA = LA->next;
 while (LA != r->next) {
  printf("编号:%d密码:%d\n", LA->id, LA->password);
  LA = LA->next;
 }
}
int Count2(Node *r) {
 Node *L = r->next;
 int count = 1;
 while (L != r) {
  count++;
  L = L->next;
 }
 return count;
} 
void YueSeFu(Node *r, int m) {
 int t = m;
 Node *LA = r;
 Node *LB = r->next;
 while (1) {
  if (Count2(LA) == 2) {
   if (t % 2 == 1) {
    printf("编号:%d 密码:%d\n\n", LB->id, LB->password);
    printf("编号:%d 密码:%d\n", LA->id, LA->password);
    break;
   } else {
    printf("编号:%d 密码:%d\n\n", LA->id, LA->password);
    printf("编号:%d 密码:%d\n", LB->id, LB->password);
    break;
   }
  } else {
   for (int i = 1; i < t; i++) {
   LA = LA->next;
   LB = LB->next; 
  }
  printf("编号:%d 密码:%d\n", LB->id, LB->password);
  if (Count2(LA) == 1) {
   break;
  }
  t = LB->password;
  LB = LB->next;
  printf("\n");
  LA->next = LB;
  }
 }
}
int main() {
 printf("开始建立循环链表: \n");
 Node *LA;
 LA = Create_Tail();
 Output(LA);
 int m; 
 printf("请输入初始密码: \n");
 scanf("%d", &m);
 printf("出队顺序: \n"); 
 YueSeFu(LA, m); 
 return 0;
}
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值