Python實現"刪除連結串列中的節點(Remove Linked List Elements)"的一種方法
阿新 • • 發佈:2019-02-09
刪除整數連結串列中值為val的節點
Example:
Input: 1->2->6->3->4->5->6, val = 6 Output: 1->2->3->4->5
1:簡單判斷節點值與val是否相等,並對判斷結果執行對應的操作
def removeElements(self, head, val): """ :type head: ListNode :type val: int :rtype: ListNode """ while head is not None and head.val==val: #保證連結串列第一個節點的值不等於val head=head.next if not head: #判斷連結串列是否為空 return None headNode = head #頭節點 while head.next is not None: if head.next.val==val: head.next = head.next.next else: head=head.next return headNode
另一種寫法(參考他人程式碼)
def removeElements(self, head, val): """ :type head: ListNode :type val: int :rtype: ListNode """ if not head: return None headNode = ListNode(1) #頭節點 headNode.next = head preNode = headNode #當前節點的上一個節點 cur = headNode.next #當前節點 while cur is not None: if cur.val==val: preNode.next = cur.next cur = preNode.next else: preNode = preNode.next cur = cur.next return headNode.next