题目描述:
给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。
写法一:递归模式
/*** Definition for singly-linked list.* class ListNode {* val: number* next: ListNode | null* constructor(val?: number, next?: ListNode | null) {* this.val = (val===undefined ? 0 : val)* this.next = (next===undefined ? null : next)* }* }*/function removeElements(head: ListNode | null, val: number): ListNode | null {if(!head){return head}head.next = removeElements(head.next,val)return head.val === val ? head.next : head};
思路讲解:
递归法:
对于给定的链表,首先对除了头节点 head以外的节点进行删除操作,然后判断 head 的节点值是否等于给定的 val。如果 head 的节点值等于 val,则 head 需要被删除,因此删除操作后的头节点为 head.next;如果 head 的节点值不等于val,则head 保留,因此删除操作后的头节点还是head。上述过程是一个递归的过程。递归的终止条件是 head 为空,此时直接返回head。当head 不为空时,递归地进行删除操作,然后判断head 的节点值是否等于val 并决定是否要删除head
写法二:迭代
/*** Definition for singly-linked list.* class ListNode {* val: number* next: ListNode | null* constructor(val?: number, next?: ListNode | null) {* this.val = (val===undefined ? 0 : val)* this.next = (next===undefined ? null : next)* }* }*/function removeElements(head: ListNode | null, val: number): ListNode | null {let node = {next:head}let currentNode =nodewhile(currentNode.next){if(currentNode.next.val === val){currentNode.next = currentNode.next.next}else{currentNode = currentNode.next}}return node.next};
思路讲解:
迭代法:
首先定义一个哨兵节点node,让他的next指向head,这样我们就不需要关心head的初始值,直接去遍历node.next进行链表的删除操作
用 currentNode 表示当前节点。如果 currentNode 的下一个节点不为空且下一个节点的节点值等于给定的val,则需要删除下一个节点。链表可以用currentNode.next=currentNode.next.next删除节点。如果 currentNode 的下一个节点的节点值不等于给定的val,则将currentNode = currentNode.next移动到下一个节点即可。当 currentNode 的下一个节点为空时,链表遍历结束,此时所有节点值等于val 的节点都被删除。最终返回 node.next 即为删除操作后的头节点。
