class Node:#定义一个节点
def __init__(self,initdata):
self.data=initdata
self.next=None
class MyList:
def __init__(self):
self.head=None #初始化链表头
def isEmpty(self):
return self.head==None
def add(self,numdata):
node=Node(numdata)
node.next=self.head
self.head=node
def remove(self,numdata):
cur = mylist.head
if cur==None:#判断是否为空
return
if cur.data==numdata:#要删的为头结点
self.head=cur.next
return
while cur.next!=None and cur.next.data!=numdata:
cur=cur.next
if cur.next.next==None and cur.next.data==numdata:#要删的为尾节点
cur.next=None
return
if cur.next==None:#没有找到要删的节点
return
temp=cur.next
cur.next=temp.next
temp=None
mylist=MyList()
mylist.add(88)
mylist.add(1)
mylist.add(11)
mylist.add(25)
mylist.add(4)
mylist.add(7)
print("head:" ,mylist.head.data)
mylist.remove(88)
cur=mylist.head
while True:
print(cur.data)
if cur.next==None:
break
cur = cur.next
python实现链表增删
最新推荐文章于 2022-01-29 23:05:12 发布