-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path203-remove-linked-list-elements.cpp
More file actions
79 lines (65 loc) · 1.93 KB
/
Copy path203-remove-linked-list-elements.cpp
File metadata and controls
79 lines (65 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// 203. Remove Linked List Elements
//
// Remove all elements from a linked list of integers that have value val.
//
// Example
// Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
// Return: 1 --> 2 --> 3 --> 4 --> 5
//
// Credits:Special thanks to @mithmatt for adding this problem and creating all test cases.
//
// Tags: Linked List
//
// https://leetcode.com/problems/remove-linked-list-elements/
#include <iostream>
#include <gtest/gtest.h>
#include <list/list.h>
using namespace std;
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
while(head && head->val == val){
head = head->next;
}
if(head == NULL) return NULL;
ListNode *prev = head;
ListNode *node = head;
while(node){
if(node->val == val){
prev->next = node->next;
delete node;
}else{
prev = node;
}
node = node->next;
}
return head;
}
};
TEST(leetcode_203_remove_linked_list_elements, Basic)
{
Solution *sol = new Solution();
ListNode *head = list_init({1, 2, 6, 3, 4, 5, 6});
ListNode *expected = list_init({1, 2, 3, 4, 5});
ListNode *result = sol->removeElements(head, 6);
EXPECT_TRUE(list_equal(expected, result));
}
TEST(leetcode_203_remove_linked_list_elements, Basic2)
{
Solution *sol = new Solution();
ListNode *head = list_init({6, 6, 6, 6, 6, 6});
ListNode *result = sol->removeElements(head, 6);
EXPECT_EQ(NULL, result);
}
TEST(leetcode_203_remove_linked_list_elements, Basic3)
{
Solution *sol = new Solution();
ListNode *head = list_init({6, 6, 6, 6, 1});
ListNode *expected = list_init({1});
ListNode *result = sol->removeElements(head, 6);
EXPECT_TRUE(list_equal(expected, result));
}
int main(int argc, char *argv[]) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}