目前只有单链表(无法查找上一个元素),后面再更新循环链表和双链表。
class SingleLinkedList:
def createList(self, raw_list):
if len(raw_list) == 0:
head = ListNode()
else:
head = ListNode(raw_list[0])
cur = head
for i in range(1, len(raw_list)):
cur.next = ListNode(raw_list[i])
cur = cur.next
return head
def removeElements(self, head, val: int):
v_head = ListNode() # 虚拟头节点
v_head.next = head
cur = v_head
while cur:
if cur and cur.next:
if cur.next.val == val:
cur.next = cur.next.next
continue
cur = cur.next
head = v_head.next
return head
def printList(self, head):
cur = s1_head
while cur:
print(cur.val)
cur = cur.next
a = [1,2,5,4,5,5]
single_linked_list = SingleLinkedList()
print("****************** before remove ***********************")
s1_head = single_linked_list.createList(a)
single_linked_list.printList(s1_head)
print("****************** after remove ***********************")
new_head = single_linked_list.removeElements(s1_head, 5)
single_linked_list.printList(new_head)