python小技巧:创建单链表及删除元素
目前只有单链表(无法查找上一个元素),后面再更新循环链表和双链表。
class SingleLinkedList:def createList(self, raw_list):if len(raw_list) == 0:head = ListNode()else:head = ListNode(raw_list[0])cur = headfor i in range(1, len(raw_list)):cur.next = ListNode(raw_list[i])cur = cur.nextreturn headdef removeElements(self, head, val: int):v_head = ListNode() # 虚拟头节点v_head.next = headcur = v_headwhile cur:if cur and cur.next:if cur.next.val == val:cur.next = cur.next.nextcontinuecur = cur.nexthead = v_head.nextreturn headdef printList(self, head):cur = s1_headwhile 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)