class ListNode:
def __init__(self, data):
self.data = data
self.next = None
@classmethod
def deletenodeo1(cls, pheadNode, pToBedeleted):
# 1.如果链表只有一个节点
# 2.如果删除的节点是链表的尾节点
# 3.多节点:把当前给定节点的next的data赋值给,再把i.next=j.next del j即可
if not pheadNode or not pToBedeleted:
return
if pToBedeleted.next: # 说明当前节点和当前节点的下一个元素 和下下一个节点都有之 第3种情况
next = pToBedeleted.next
next__next = pToBedeleted.next.next
pToBedeleted.data = next.data
pToBedeleted.next = next__next
del next
elif pheadNode == pToBedeleted: # 删除头节点
del pheadNode
else: # 删除尾节点
# O(n)遍历删除最后一个节点
while pheadNode.next != pToBedeleted:
pheadNode = pheadNode.next
pheadNode.next = None
del pToBedeleted
a = ListNode('a')
b = ListNode('b')
c = ListNode('c')
d = ListNode('d')
root = a
# a.next = b
# b.next = c
# c.next = d
def travese(root):
while root:
print(root.data)
root = root.next
# 1.删除尾节点
ListNode.deletenodeo1(root, a)
travese(root)