Remove linked list elements (Force Link No.203)

I haven’t really run a linked list in all these years, and linked lists are defined by structures. Structure definition:

struct ListNode { int val; ListNode* next; ListNode() : val(0), next(nullptr) {} val(x), next(nullptr) {} ListNode(int x, ListNode* next) : val(x), next(next) {} };Copy the code

Initialize struct:

The Date variable is defined and initialized by specifying the name of the variable, followed by an assignment operator and an initializer, as follows:

//ListNode a; //ListNode b = ListNode(2); //ListNode c = ListNode(2, &b); I haven't figured it out yet...Copy the code

Since you are returning a head node and have only one head pointer, you will inevitably run out of Pointers (headers are difficult to handle). You can define an additional header (true header) to unify the operation of the node. Code:

ListNode* removeElements(ListNode* head, int val) { ListNode* dummyHead = new ListNode(0); DummyHead ->next = head; ListNode* cur = dummyHead; 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; }Copy the code

When I was running on VS, the two lines of delete free memory code could only run if it was commented out. It seems to be related to a memory leak. Dig a hole and fill it later. 6.1 forgot to post yesterday. embarrassed