// 删除单链表指定元素5 #include#include using namespace std; //节点定义: struct ListNode { int val; ListNode* next; ListNode(int x) : val(x), next(nullptr) {} }; class Solution { public: ListNode* removeElements(ListNode* head, int val) { ListNode* dummyHead = new ListNode(0);//创造个虚拟头节点,便于操作链表 dummyHead->next = head; ListNode* cur = dummyHead; while (cur->next != NULL) { if (cur->next->val == val) { ListNode* tmp = cur->next; cur->next = cur->next->next; delete tmp; } else { cur = cur->next; } } head = dummyHead->next;//如果是删除头节点就需要这行 delete dummyHead; return head; } }; //创造节点 void CreateList(ListNode *head) { vector nums = { 1,2,3,3,1,5,1 }; ListNode *p = head; for (int i = 1; i < nums.size(); ++i) { p->next = new ListNode(nums[i]); p = p->next; } } //输出节点 void PrintList(ListNode *head) { ListNode *p = head; while (p != NULL) { cout << p->val << endl; p = p->next; } } int main() { ListNode* head = new ListNode(1);//创造头节点 CreateList(head); Solution List; ListNode* ret = List.removeElements(head, 5); PrintList(ret); system("pause"); return 0; }



