约瑟夫环问题及python与c++实现效率对比

约瑟夫环是一个数学的应用问题:已知n个人(以编号1,2,3...n分别表示)围坐在一张圆桌周围。从编号为k的人开始报数,数到m的那个人出列;他的下一个人又从1开始报数,数到m的那个人又出列;依此规律重复下去,直到圆桌周围的人全部出列。

python实现:

# 单链表节点
class LinkNode:
def __init__( self, value ):
self.value = value
self.next = None # 创建循环单链表,值从1开始
def create_cycle( total ):
head = LinkNode( 1 )
prev = head
index = 2
while total - 1 > 0:
curr = LinkNode( index )
prev.next = curr
prev = curr
index += 1
total -= 1
curr.next = head
return head # 模拟约瑟夫环过程,从1开始计数
def run( total, m ):
assert total >= 0, 'total should lq 0'
assert m >= 0, 'm should lt 0'
node = create_cycle( total )
prev = None
start = 1
index = start
while node and node.next:
if index == m:
print( 'pop:' + node.value )
prev.next = node.next
node.next = None
node = prev.next
       index = start
else:
prev = node
node = node.next
index += 1 run( 5, 2 )

c++实现如下:

#include <stdio.h>
#include <stdlib.h> #define COUNT_INIT 1 // 计数起点 typedef struct LINKNODE
{
int value;
struct LINKNODE* next;
}LinkNode, *LinkNodePtr; // 创建结点
LinkNodePtr createNode( int value )
{
LinkNodePtr node = ( LinkNodePtr )malloc( sizeof( LinkNode ) );
node->value = value;
return node;
} // 创建循环单链表
LinkNodePtr createCycle( int total )
{
int index = 1;
LinkNodePtr head = NULL, curr = NULL, prev = NULL;
head = createNode( index );
prev = head; while( --total > 0 )
{
curr = createNode( ++index );
prev->next = curr;
prev = curr;
}
curr->next = head; // 链表尾结点指向头结点, 构成循环链表
return head;
} // 数到m, 节点出列, 下一个节点继续从1开始数. m不可与COUNT_INIT同值
void run( int total, int m )
{
LinkNodePtr node = createCycle( total );
LinkNodePtr prev = NULL;
int index = COUNT_INIT; while( node && node->next )
{
if( index == m )
{
printf( "pop:%d\n", node->value );
prev->next = node->next;
node->next = NULL;
free( node );
node = prev->next;
index = COUNT_INIT;
}
else
{
prev = node;
node = node->next;
index++;
}
}
}

  

上一篇:bzoj 2653 middle 二分答案 主席树判定


下一篇:LeetCode--No.004 Median of Two Sorted Arrays