Problem Description
Magician hands of A, 2,3 ...... J, Q, K thirteen spades playing cards. Before performing magic, magicians have stacked them in a certain order good (have color side down) magic show for the process: the beginning, the magician number 1, and then goes to the top of the card turned over , spades a; then place it on your desktop; second, the number of magicians 1,2; the first card into the bottom card, the second card is turned over, just spades 2; the third time, the magician number 1,2,3; 1,2-card will turn into the bottom of these cards, the third card is turned over just spades 3; ...... until all cards have turned out so far. the original order of the cards is to ask how.
Correct result: [1, 8, 2, 5, 10, 3, 12, 11, 9, 4, 7, 6, 13]
solution
1. List
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. round robin list
class Node:
"""节点"""
def __init__(self, value):
self.data = value
self.next = None
def __repr__(self):
return f'Node: {self.data}'
class CircularLinkedList:
"""单循环链表"""
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 # 取得头部节点
print('Head', end='')
while True:
print('-->', p.data, end='')
if p is self.rear: # 到达尾部停止
break
p = p.next
print('-->Finish')
def solution_circular_linked_list():
pokers = CircularLinkedList()
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)