Skip to the content.

Ex18 删除链表的结点

题目描述

给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。返回删除后的链表的头节点。

注意:此题对比原题有改动

解题思路

这个题就比较简单了。

代码

struct ListNode *
deleteNode (struct ListNode *head, int val)
{
  if (!head)
    return;
  if (head->val == val)
    return head->next;
  struct ListNode *pre = head, *cur;
  if (head->next)
    cur = head->next;
  while (cur && cur->val != val)
    {
      cur = cur->next;
      pre = pre->next;
    }
  if (!cur)
    return head;
  pre->next = cur->next;
  // free(cur);
  return head;
}

结果

执行结果:通过

执行用时:8 ms, 在所有 C 提交中击败了48.97%的用户

内存消耗:6 MB, 在所有 C 提交中击败了29.35%的用户