Skip to content

Commit d563d29

Browse files
committed
🚀 21-Jul-2020
1 parent a7a8b2f commit d563d29

File tree

2 files changed

+112
-0
lines changed

2 files changed

+112
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
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 numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
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+
};

0 commit comments

Comments
 (0)