203. 移除链表元素

52 阅读1分钟

203. 移除链表元素

已解答

简单

相关标签

premium lock icon相关企业

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

 

示例 1:

输入: head = [1,2,6,3,4,5,6], val = 6
输出: [1,2,3,4,5]

示例 2:

输入: head = [], val = 1
输出: []

示例 3:

输入: head = [7,7,7,7], val = 7
输出: []

 

提示:

  • 列表中的节点数目在范围 [0, 104] 内
  • 1 <= Node.val <= 50
  • 0 <= val <= 50

面试中遇到过这道题?

1/5

通过次数

919,614/1.6M

通过率

59.1%

题解:

struct ListNode* removeElements(struct ListNode* head, int val) {
    if (head == NULL)
    {
        return NULL;
    }

    struct ListNode* pre;
    struct ListNode* del;
    struct ListNode* now;

    while (head != NULL && head->val == val)//虽然上面有if判断是否head为NULL,
                                           //但是循环过程中head有可能原来不是NULL,后面变成NULL,
                                          //因此还是应该先判断head != NULL,再写后面的val,顺序不能乱
    {
        pre = head;
        head = head->next;
        free(pre);
    }

    if (head == NULL)
    {
        return NULL;
    }

    pre = head;
    now = pre->next;
    while (now != NULL)
    {
        if (now->val == val)
        {
            del = now;
            now = now->next;
            free(del);
            pre->next = now;
        }
        else
        {
            pre = pre->next;
            now = now->next;
        }
    }

    return head;
}

bug: 1.Line 18: Char 16: runtime error: member access within null pointer of type 'struct ListNode' [solution.c] 在指针内部进行成员访问(access:访问, whthin:在内部) 试图访问空指针的val: 我写的是while (head->val == val && head != NULL),会先判断第一个,再判断第二个,应该先判断是否为null,修改后通过。