题目:写一个程序,用来存储学生的姓名和年龄,请用链表实现
1 #!/usr/bin/env python 2 3 class StudentNode(object): 4 def __init__(self, name, age, next_=None): 5 self.student = [name, age] 6 self.next = next_ 7 8 class StudentList(object): 9 def __init__(self): 10 self.head = None 11 self.num = 0 12 13 def prepend(self, name, age): 14 self.head = StudentNode(name, age, self.head) 15 self.num += 1 16 17 def bianli(self): 18 p = self.head 19 li = [] 20 while p: 21 li.append(p.student) 22 p = p.next 23 return li 24 25 if __name__ == '__main__': 26 s = StudentList() 27 s.prepend("xuqiang",18) 28 s.prepend("lisa",20) 29 print(s.bianli())
结果:
[['lisa', 20], ['xuqiang', 18]]