Problem:
Solution:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode *curr = head;
// Base case
while (curr != NULL && curr -> val == val) {
curr = curr -> next;
head = curr;
}
// Iteration start.
while (curr != NULL) {
if (curr -> next != NULL && curr -> next -> val == val)
curr -> next = curr -> next -> next;
else
curr = curr -> next;
}
return head;
}
};
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
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5
Solution:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode *curr = head;
// Base case
while (curr != NULL && curr -> val == val) {
curr = curr -> next;
head = curr;
}
// Iteration start.
while (curr != NULL) {
if (curr -> next != NULL && curr -> next -> val == val)
curr -> next = curr -> next -> next;
else
curr = curr -> next;
}
return head;
}
};
==========
/**
* Definition for singly-linked list.
* 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) {
if (head == NULL) {
return NULL;
}
ListNode* dummy = new ListNode(-1);
ListNode* tmp = dummy;
while (head != NULL) {
if (head -> val != val) {
tmp -> next = head;
tmp = tmp -> next;
}
head = head -> next;
tmp -> next = NULL;
}
return dummy -> next;
}
};
No comments:
Post a Comment