删除链表中等于给定值 val 的所有节点。
示例:
输入: 1->2->6->3->4->5->6, val = 6 输出: 1->2->3->4->5
——题目难度:简单
解题代码
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
//创建头结点
ListNode* pre = new ListNode(0); //pre指向头结点
ListNode* ans = pre;
pre->next = head;
ListNode* cur = head;
while (cur) {
if (cur->val == val) {
pre->next = cur->next;
delete cur;
cur = pre->next;
} else {
pre = cur;
cur = cur->next;
}
}
return ans->next;
}
};