class Child(object):
first = None
def __init__(self, no=None, pNext=None):
self.no = no
self.pNext = pNext
def addChild(self):
cur = None
for i in range(4):
child = Child(i + 1) # 实例化新的孩子
if i == 0: # 如果是
self.first = child
child.pNext = self.first
cur = self.first
else:
cur.pNext = child
child.pNext = self.first
cur = cur.pNext
def showChild(self):
cur = self.first
while cur.pNext != self.first:
print("当前孩子的编号是:%s" % cur.no)
cur = cur.pNext
print("当前孩子的编号是:%s" % cur.no)
def countChild(self, m, k):
tail = self.first
# 当tail退出循环的时候,tail已经跑到指向first的节点
while tail.pNext != self.first:
tail = tail.pNext
# 解决指定数数的孩子的起始位置的问题
for i in range(k-1):
tail = tail.pNext
self.first = self.first.pNext
while tail != self.first:
# 数两下(迈一步),tail指向first后一个节点,first指向其前一个节点
for i in range(m-1):
tail = tail.pNext
self.first = self.first.pNext
# 因为取出数中的节点,所以要将断裂的链表连接起来
self.first = self.first.pNext
tail.pNext = self.first
print("最终身下的孩子的编号是:%s" % self.first.no)
cc = Child()
cc.addChild()
cc.showChild()
cc.countChild(4, 1)