数据结构4:移除链表元素

    科技2022-08-11  97

    题目描述

    解答

    本题的方法是在头节点前创建一个哨兵节点即可,比较简单。

    struct ListNode* removeElements(struct ListNode* head, int val){ if(!head) return false; struct ListNode* guard=malloc(sizeof(struct ListNode));//动态一个哨兵 guard->next=head; struct ListNode *pre=guard,*p=head; while(p&&pre) { if(p->val==val) { pre->next=p->next; p=pre->next; } else { p=p->next; pre=pre->next; } } head=guard->next; free(guard); return head; }
    Processed: 0.021, SQL: 8