# 魔术师发牌问题 -- python实现

### 解决方案

##### 1. 列表
def solution_list():
pokers = [0 for _ in range(13)]         # 初始化
count = len(pokers)                     # 纸牌总数
index = -1

for num in range(1, 14):
i = 0                               # 计数
while i < num:
index = (index + 1) % count     # 索引向前一步(可循环)
if pokers[index] == 0:          # 当前元素为0时才计数, 不为0则跳过
i += 1
pokers[index] = num

print('#' * 50)
print(f'\n牌组: {pokers}\n')
print('#' * 50)

##### 2. 单循环链表
class Node:
"""节点"""

def __init__(self, value):
self.data = value
self.next = None

def __repr__(self):
return f'Node: {self.data}'

"""单循环链表"""
def __init__(self):
self.rear = None    # 尾节点

def is_empty(self):
return self.rear is None

def append(self, elem):
"""尾插法"""
temp = Node(elem)
if self.rear is None:
temp.next = temp
self.rear = temp
else:
temp.next = self.rear.next
self.rear.next = temp
self.rear = temp

def print_all(self):
"""
按顺序打印全部节点
"""
if self.is_empty():
return
p = self.rear.next      # 取得头部节点
while True:
print('-->', p.data, end='')
if p is self.rear:      # 到达尾部停止
break
p = p.next
print('-->Finish')

for _ in range(13):
pokers.append(0)

temp = pokers.rear
for num in range(1, 14):
i = 0
while i < num:
temp = temp.next
if temp.data == 0:
i += 1
temp.data = num

print('#' * 50)
print('\n牌组: ')
pokers.print_all()
print('\n' + '#' * 50)

posted on 2019-12-20 11:10  雷子-LL  阅读(299)  评论(0编辑  收藏  举报