python 实现单项循环链表
自定义单项循环链表
class Item(object):
def __init__(self,data,next=None,):
self.data = data
self.next = next
class CycleLinkedList(object):
def __init__(self):
self.first = Item(None,next=None)
self.first.next = self.first
def add(self,N,):
sign = self.first
for data in range(1,N+1):
if sign.data == None:
sign.data = data
else:
while True:
if sign.next == self.first:
break
sign = sign.next
body = Item(data)
sign.next = body
body.next = self.first
def move(self,K):
sign1 = self.first
sign2 = self.first
while True:
if sign2.next == self.first:
break
sign2 = sign2.next
while K >1:
sign1 = sign1.next
sign2 = sign2.next
K -= 1
return sign1,sign2
def pop(self,sign1,sign2,M):
res = []
while sign1 != sign2:
num = M
while num > 1:
sign1 =sign1.next
sign2 = sign2.next
num -= 1
res.append(sign1.data)
sign2.next = sign1.next
sign1 = sign1.next
res.append(sign1.data)
return res
def show(self):
sign = self.first
res = []
while True:
res.append(sign.data)
if sign.next == self.first:
break
sign = sign.next
return res
def main(N,K,M):
peoples = CycleLinkedList()
peoples.add(N)
sign1,sign2 = peoples.move(K)
print(peoples.pop(sign1,sign2,M))
if __name__ == '__main__':
main(8,1,4)