题目描述:

给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。
image.png

写法一:递归模式

  1. /**
  2. * Definition for singly-linked list.
  3. * class ListNode {
  4. * val: number
  5. * next: ListNode | null
  6. * constructor(val?: number, next?: ListNode | null) {
  7. * this.val = (val===undefined ? 0 : val)
  8. * this.next = (next===undefined ? null : next)
  9. * }
  10. * }
  11. */
  12. function removeElements(head: ListNode | null, val: number): ListNode | null {
  13. if(!head){
  14. return head
  15. }
  16. head.next = removeElements(head.next,val)
  17. return head.val === val ? head.next : head
  18. };

思路讲解:

递归法:
对于给定的链表,首先对除了头节点 head以外的节点进行删除操作,然后判断 head 的节点值是否等于给定的 val。如果 head 的节点值等于 val,则 head 需要被删除,因此删除操作后的头节点为 head.next;如果 head 的节点值不等于val,则head 保留,因此删除操作后的头节点还是head。上述过程是一个递归的过程。递归的终止条件是 head 为空,此时直接返回head。当head 不为空时,递归地进行删除操作,然后判断head 的节点值是否等于val 并决定是否要删除head

写法二:迭代

  1. /**
  2. * Definition for singly-linked list.
  3. * class ListNode {
  4. * val: number
  5. * next: ListNode | null
  6. * constructor(val?: number, next?: ListNode | null) {
  7. * this.val = (val===undefined ? 0 : val)
  8. * this.next = (next===undefined ? null : next)
  9. * }
  10. * }
  11. */
  12. function removeElements(head: ListNode | null, val: number): ListNode | null {
  13. let node = {
  14. next:head
  15. }
  16. let currentNode =node
  17. while(currentNode.next){
  18. if(currentNode.next.val === val){
  19. currentNode.next = currentNode.next.next
  20. }else{
  21. currentNode = currentNode.next
  22. }
  23. }
  24. return node.next
  25. };

思路讲解:

迭代法:
首先定义一个哨兵节点node,让他的next指向head,这样我们就不需要关心head的初始值,直接去遍历node.next进行链表的删除操作
用 currentNode 表示当前节点。如果 currentNode 的下一个节点不为空且下一个节点的节点值等于给定的val,则需要删除下一个节点。链表可以用currentNode.next=currentNode.next.next删除节点。如果 currentNode 的下一个节点的节点值不等于给定的val,则将currentNode = currentNode.next移动到下一个节点即可。当 currentNode 的下一个节点为空时,链表遍历结束,此时所有节点值等于val 的节点都被删除。最终返回 node.next 即为删除操作后的头节点。