有人让我实现一个链表,结果我出丑了,不愧是半路出家啊!
百度了一下链表的定义,自己实现了一下单向链表:
# 链表类 python实现
# 单向链表
import random
import time
# 一环的实现
class Hoop(object):
def __init__(self, content):
self.content = content
self.next = None
def print_hoop(self):
print(self.content)
class OneWayLinkedList(object):
def __init__(self):
first = Hoop(None)
self.first = first
def get_last(self):
last_one = self.first
while True:
# time.sleep(1)
# print("last_one 0", last_one, last_one.content, last_one.next)
if last_one.next:
last_one = last_one.next
else:
break
return last_one
def push(self, content):
new = Hoop(content)
last_one = self.get_last()
# print("last_one 1", last_one, last_one.content, last_one.next)
last_one.next = new
def printl(self):
last_one = self.first
while True:
# time.sleep(1)
# print("last_one 2", last_one, last_one.content, last_one.next)
if last_one != self.first:
last_one.print_hoop()
if last_one.next:
last_one = last_one.next
else:
break
# return last_one
# 双向链表 ToDo
# 循环链表 ToDo
if __name__ == '__main__':
# print(get_index())
# a = Hoop()
a = OneWayLinkedList()
# a.push(1)
# # 测试及验证
input_list = []
for i in range(10):
try:
i = random.randint(0, 100)
a.push(i)
input_list.append(i)
except Exception as e:
print(e)
break
a.printl()
print(input_list)
pass