Edge
  • Introduction
  • 文章
    • 如何将 emoji 当成单色 icon 使用
    • 在 web 使用 JavaScript 模块
    • 从零开始写一个 Promise 库
    • 魔幻语言 JavaScript 系列之类型转换、宽松相等以及原始值
    • React 整洁代码最佳实践
    • 魔幻语言 JavaScript 系列之 call、bind 以及上下文
    • 编写扁平化的代码
    • ES6 Promise:模式与反模式
    • 在 Node.js 中使用原生 ES 模块
    • 在工作中学习
    • JavaScript 中的匿名递归
    • 面向初学者的高阶组件介绍
    • CSS Animations vs Web Animations API
    • JavaScript 异常的防范与监控
    • 喜欢用 Git 做的一些小事
    • 移除在 ESM 模式生成的严格模式
    • 编写现代 JavaScript 代码
    • JavaScript 模块化现状
    • JS/React 开发者的 Atom 终极配置
    • 使用 ES6 的浏览器兼容性问题
    • 为什么是 JSONP
    • 实现不定尺寸图片居中的几种方式
    • Base64 简要笔记及其他
    • 关于内存对齐的一点注解
    • 康威生命游戏的简单实现
    • 使用双端队列模拟动态数组的部分功能
    • 三种变长编码方法的 C 实现
  • 聚沙成塔
    • Node.js
      • 包管理器
    • 基于 OS X 开发指南
    • OS X 小技巧
    • 基于 Windows 开发指南
    • Web Tools
    • Service Worker
    • vim
    • shell
    • 奇技
    • 程序员
    • BFC
    • 事件循环
    • 获取自定义全局变量
    • 颜色格式转换 rgb -> hex
    • 页面间 post 传参
    • 函数重载
    • Tree shaking
    • RequireJS tips
  • 算法
    • 约瑟夫问题
    • 简单排序
    • 快速排序
    • 快速排序优化
    • 三路快排和选择
    • 裴波那契
  • ECMAScript
    • 原型
    • Object.is
  • ES6+
    • ES6 Modules
    • import & export
  • React
    • setState
    • react 与 iscroll 的点击问题
    • pureRender
  • git
    • 重写提交信息
    • http 记住密码
  • 拾遗
    • 拾遗
Powered by GitBook
On this page
  • linked list
  • C
  • Javascript
  • Python
  • Java
  1. 算法

约瑟夫问题

July 8th, 2014

linked list

C

struct node {
  item item;
  struct node* next;
}

struct node* head = malloc(sizeof(*head));
head->item = 1;
head->next = head;

C full-edition

// josephus_problem.c
#include <stdio.h>
#include <stdlib.h>

typedef struct node* link;
struct node {
  int item;
  link  next;
};

int main(int argc, char *argv[]) {
  int i, N = atoi(argv[1]), M = atoi(argv[2]);
  link head = malloc(sizeof(struct node)), x;
  head->item = 1;
  head->next = head;

  for (i = 2, x = head; i <= N; i++) {
    x = (x->next = malloc(sizeof *x));
    x->item = i;
  }
  x->next = head;

  while(x != x->next) {
    for (i = 1; i < M; i++) x = x->next;
    printf("%d ", x->next->item);
    x->next = x->next->next;
  }

  printf("\nLeft: %d\n", x->item);
}

Javascript

construct function

function Node(item, next) {
  this.item = item;
  this.next = next;
}

var head = new Node(1);
head.next = head;

Python

class Node():
  def __init__(self, item, next):
    self.item = item
    self.next = mext
  }

head = Node(1)
head.next = head

Java

class Node {
  int item;
  Node next;
}

Node head = new Node();
head.item = 1;
head.next = head;
Previous算法Next简单排序

Last updated 6 years ago