File tree Expand file tree Collapse file tree
competitive programming/leetcode Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ Remove all elements from a linked list of integers that have value val.
2+
3+ Example:
4+
5+ Input: 1 ->2 ->6 ->3 ->4 ->5 ->6 , val = 6
6+ Output: 1 ->2 ->3 ->4 ->5
7+
8+
9+
10+
11+
12+ /* *
13+ * Definition for singly-linked list.
14+ * struct ListNode {
15+ * int val;
16+ * ListNode *next;
17+ * ListNode() : val(0), next(nullptr) {}
18+ * ListNode(int x) : val(x), next(nullptr) {}
19+ * ListNode(int x, ListNode *next) : val(x), next(next) {}
20+ * };
21+ */
22+ class Solution {
23+ public:
24+ ListNode* removeElements (ListNode* head, int val) {
25+ if (!head) return head;
26+ while (head->val ==val && head->next !=NULL ){
27+ ListNode* tmp=head;
28+ head=head->next ;
29+ delete tmp;
30+ }
31+ if (head->val ==val){
32+ // last node
33+ delete head;
34+ head=NULL ;
35+ return head;
36+ }
37+ ListNode *curr=head, *prev=head;
38+ while (curr->next !=NULL ){
39+ if (curr->val ==val){
40+ prev->next =curr->next ;
41+ delete curr;
42+ curr=prev->next ;
43+ } else {
44+ prev=curr;
45+ curr=curr->next ;
46+ }
47+ }
48+ // last node
49+ if (curr->val ==val){
50+ prev->next =NULL ;
51+ delete curr;
52+
53+ }
54+ return head;
55+ }
56+ };
Original file line number Diff line number Diff line change 1+ Remove all elements from a linked list of integers that have value val.
2+
3+ Example:
4+
5+ Input: 1 ->2 ->6 ->3 ->4 ->5 ->6 , val = 6
6+ Output: 1 ->2 ->3 ->4 ->5
7+
8+
9+
10+
11+
12+ /* *
13+ * Definition for singly-linked list.
14+ * struct ListNode {
15+ * int val;
16+ * ListNode *next;
17+ * ListNode() : val(0), next(nullptr) {}
18+ * ListNode(int x) : val(x), next(nullptr) {}
19+ * ListNode(int x, ListNode *next) : val(x), next(next) {}
20+ * };
21+ */
22+ class Solution {
23+ public:
24+ ListNode* removeElements (ListNode* head, int val) {
25+ if (!head) return head;
26+ while (head->val ==val && head->next !=NULL ){
27+ ListNode* tmp=head;
28+ head=head->next ;
29+ delete tmp;
30+ }
31+ if (head->val ==val){
32+ // last node
33+ delete head;
34+ head=NULL ;
35+ return head;
36+ }
37+ ListNode *curr=head, *prev=head;
38+ while (curr->next !=NULL ){
39+ if (curr->val ==val){
40+ prev->next =curr->next ;
41+ delete curr;
42+ curr=prev->next ;
43+ } else {
44+ prev=curr;
45+ curr=curr->next ;
46+ }
47+ }
48+ // last node
49+ if (curr->val ==val){
50+ prev->next =NULL ;
51+ delete curr;
52+
53+ }
54+ return head;
55+ }
56+ };
You can’t perform that action at this time.
0 commit comments