删除整数链表中值为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
算法题来自:https://leetcode-cn.com/problems/remove-linked-list-elements/description/