剑指 Offer 18. 删除链表的节点

image.png

遍历

  1. public class Solution {
  2. public ListNode deleteNode(ListNode head, int val) {
  3. // 如果是空链表,直接返回空
  4. if (head == null) return null;
  5. // 如果要删除的节点是第一个,直接返回 head.next
  6. if (head.val == val) return head.next;
  7. // 记录前一个节点
  8. ListNode pre = head;
  9. // 记录当前节点
  10. ListNode cur = head.next;
  11. while (true) {
  12. // 如果当前节点是要删除的节点
  13. if (cur.val == val) {
  14. // 令上一个节点的 next 指向当前节点的 next,停止循环
  15. pre.next = cur.next;
  16. break;
  17. }
  18. // 往前进一步
  19. pre = pre.next;
  20. cur = cur.next;
  21. }
  22. return head;
  23. }
  24. }

遍历,增加伪头节点

执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户 内存消耗:37.5 MB, 在所有 Java 提交中击败了93.76%的用户

  1. class Solution {
  2. public ListNode deleteNode(ListNode head, int val) {
  3. // 使用伪头节点
  4. ListNode temp = new ListNode(0);
  5. temp.next = head;
  6. // 记录前一个节点
  7. ListNode pre = temp;
  8. // 记录当前节点
  9. ListNode cur = temp.next;
  10. while (true) {
  11. // 如果当前节点是要删除的节点
  12. if (cur.val == val) {
  13. // 令上一个节点的 next 指向当前节点的 next,停止循环
  14. pre.next = cur.next;
  15. break;
  16. }
  17. // 往前进一步
  18. pre = pre.next;
  19. cur = cur.next;
  20. }
  21. return temp.next;
  22. }
  23. }

递归

执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户 内存消耗:37.8 MB, 在所有 Java 提交中击败了66.79%的用户

class Solution {
    public ListNode deleteNode(ListNode head, int val) {
        if (head == null) return null;

        if (head.val == val) return head.next;
        else head.next = deleteNode(head.next, val);

        return head;
    }
}