----------------------------------------链式操作----------------------------------------
class Hero(object):
def __init__(self, no=None, name=None, nickname=None, pNext=None):
self.no = no
self.name = name
self.nickname = nickname
self.pNext = pNext
def addHero(head, hero):
cur = head
# 第一种 添加到链表后面
# while cur.pNext != None:
# cur = cur.pNext
# cur.pNext = hero
###第二种 指定添加
while cur.pNext != None:
### 找到了指定的位置, 直接跳出while循环
if cur.pNext.no > hero.no:
break
### 没有找到的话, 继续找
cur = cur.pNext
hero.pNext = cur.pNext #hero为中间需要插入的对象,先把当前指针指向的对象丢给“被插入的对象”
cur.pNext = hero #然后把“被插入的对象” 变成当前指针指向的值,赋值操作和上面的不能颠倒。
def getAll(head):
cur = head
while cur.pNext != None:
cur = cur.pNext
print('编号是:%s, 姓名是:%s, 外号是%s' % (cur.no, cur.name, cur.nickname) )
head = Hero()
hero1 = Hero(1, '美队', 'American Captain')
# print(hero1)
addHero(head, hero1)
hero2 = Hero(2, '钢铁侠', 'Iron-Man')
addHero(head, hero2)
hero4 = Hero(4, '蜘蛛侠', 'Spider-Man')
addHero(head, hero4)
hero3 = Hero(3, '雷神', 'Thor')
addHero(head, hero3)
getAll(head)