leetcode-Remove Linked List Elements
题目链接:
https://leetcode.com/problems/remove-linked-list-elements/
分析:
增加一个哑节点,可以简化删除节点是否是头节点的操作,具体实现代码如下图所示:
class Solution { public: ListNode* removeElements(ListNode* head, int val) { if(head == NULL) { return head; } ListNode dummy(-1); dummy.next = head; ListNode *cur = head; ListNode *pre = &dummy; while(cur != NULL) { ListNode *next = cur->next; if(cur->val == val) { pre->next = next; delete cur; cur = next; } else { pre = cur; cur = next; } } return dummy.next; } };