Topic
Remove all elements from a linked list of integers, that has value Val.
Example
given:1–> 2–> 6–> 3–> 4–> 5–> 6, val = 6
Return:1–> 2–> 3–> 4–> 5
Ideas
The delete operation of the linked list node.
Code
/ *---------------------------------------* Date: 2015-05-01* sjf0115* title: 203.Remove Linked List elements* website: htt ps://leetcode.com/problems/remove-linked-list-elements/* Result: ac* Source: leetcode* Blog:-----------------------------------------* *#include <iostream>#include <vector>using namespace STD;structlistnode{intVal ListNode *next; ListNode (intx): Val (x), Next (nullptr){}};classSolution { Public: listnode* removeelements (listnode* head,intVal) {if(Head = =nullptr){return nullptr; }//ifListNode *dummy =NewListNode (0); Dummy->next = head; listnode* pre = dummy; listnode* cur = head; listnode* tmp; while(cur) {if(Cur->val = = val) {tmp = cur; Pre->next = cur->next;Deletetmp Cur = pre->next; }//if Else{pre = cur; Cur = cur->next; }//else}//while returndummy->next; }};intMain () {solution solution; listnode* head =NewListNode (1); listnode* Node1 =NewListNode (5); listnode* Node2 =NewListNode (2); listnode* Node3 =NewListNode (1); listnode* node4 =NewListNode (4); listnode* NODE5 =NewListNode (1); Head->next = Node1; Node1->next = Node2; Node2->next = Node3; Node3->next = Node4; Node4->next = NODE5; Head = solution.removeelements (head,6); while(head) {cout<//while}
Run Time
[Leetcode]203.remove Linked List Elements