Given the head of a linked list and an integer val, remove all the nodes of the linked list that has N o d e . v a l = = v a l Node.val == val Node.val==val, and return the new node.
example
Input: head = [1, 2, 6, 3, 4, 5, 6], val = 6
Output: [1, 2, 3, 4, 5]
// 203. remove linked list element
/*
Given the head of a linked list and an integer val, remove all the nodes of the linked list that
has Node.val == val, and return the new head of the linked list.
*/
#include
#include
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode *dummy = new ListNode(0);
dummy->next = head;
ListNode *prev = dummy;
ListNode *node;
while (prev->next) {
node = prev->next;
if (node->val == val) {
prev->next = node->next;
delete node;
} else {
prev = prev->next;
}
}
return dummy->next;
}
};
// generate a linklist inters of an array nums
ListNode* generateLinkList(vector& nums) {
ListNode *head = new ListNode(nums[0]);
ListNode *node = head;
for (int i = 1; i < nums.size(); i++) {
node->next = new ListNode(nums[i]);
node = node->next;
}
return head;
}
int main()
{
vector nums = {1, 2, 6, 3, 4, 5, 6};
ListNode *head = generateLinkList(nums);
ListNode *cur_node = head;
cout << "original linklist: ";
while (cur_node) {
cout << cur_node->val << " ";
cur_node = cur_node->next;
}
cout << endl;
Solution s;
ListNode *new_head = s.removeElements(head, 6);
cout << "new linklist: ";
while (new_head) {
cout << new_head->val << " ";
new_head = new_head->next;
}
cout << endl;
return 0;
}
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
if (head == nullptr) return head;
head->next = removeElements(head->next, val);
return head->val == val ? head->next : head;
}
};
It is easy for us to see the recursive version for this problem is obviously short than the iterative version.