数据结构之python实现循环双链表实例
题目如下:
python实现:
import random class DLNode: def __init__(self,data): self.data = data self.next = None self.prev = None class CDLL: def __init__(self): self.head = DLNode(None) def CreateDLL(self): DataList = [高术,马喆,季罔,阮宫岛,奚佳加,毛溉,安倬,束萝] cNode = self.head for i in DataList: element = DLNode(i) cNode.next = element element.prev = cNode element.next = self.head self.head.prev = element cNode = cNode.next def GetLength(self): cNode = self.head length = 0 while cNode.next !=self.head : length = length+1 cNode = cNode.next return length def Find(self): pos = 0 cNode = self.head name = (input(主持人指定玫瑰当前持有者:)) while cNode.next != self.head and cNode.data != name: cNode = cNode.next pos+=1 if cNode.data == name: return cNode else: print(无次参与者) 判断冠、亚、季函数 def JudgeWinner(self,count,tNode): if count == 1: print("此轮比赛的季军是:",tNode.data) elif count == 2: print("此轮比赛的亚军是:",tNode.data) elif count == 3: print("此轮比赛的冠军是:",tNode.data) else: print("输入有误") def TransRule(self,sign,transNum,count,tNode): cNode = tNode #tNode即为主持人指定的玫瑰持有者 pNode = cNode.prev if sign == "右": while transNum != 0: if cNode == self.head: pNode = cNode cNode = cNode.next pNode = cNode cNode = cNode.next transNum = transNum-1 if cNode == self.head: pNode = cNode cNode = cNode.next elif sign == "左": while transNum != 0: if cNode == self.head: pNode = pNode.prev cNode = cNode.prev pNode = pNode.prev cNode = cNode.prev transNum = transNum-1 if cNode == self.head: pNode = pNode.prev cNode = cNode.prev else: print("请正确输入") self.JudgeWinner(count,cNode) pNode.next = cNode.next cNode.next.prev = pNode del cNode cNode = pNode.next def TraverseCSLL(self): print("本轮参与的市民共有",self.GetLength(),"人,分别为:") cNode = self.head.next while cNode.next != self.head: print(cNode.data,->,end= ) cNode = cNode.next print(cNode.data) def RoseGame(self): total = self.GetLength() count = 1 while count <= 3: self.TraverseCSLL() cNode = self.Find() pNode = cNode.prev sign = input("请主持人指定的玫瑰持有者决定传递方向(左或右):") randomNum = random.randint(1,100) print("主持人第",count,"轮随机选的数为:", randomNum) transNum = randomNum % total print("传递次数为:",transNum) self.TransRule(sign,transNum,count,cNode) count = count+1 total = self.GetLength() print("game over") if __name__ == "__main__": CDL = CDLL() CDL.CreateDLL() CDL.RoseGame()
结果如下:
上一篇:
IDEA上Java项目控制台中文乱码