无算法题解:
/**
* 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) {
ListNode *r = new ListNode;
r->next = NULL;
ListNode *m = r;
while(head!=NULL)
{
if(head->val == val){
head = head->next;
continue;
}
ListNode *n = new ListNode;
n->val = head->val;
m->next = n;
m=n;
head= head->next;
}
r=r->next;
return r;
}
};
用哑结点:
/**
* 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) {
ListNode*dummynode = new ListNode;
dummynode->next = head;
ListNode*p = dummynode;
while(p->next!=NULL)
{
if(p->next->val == val)
{
p->next = p->next->next;
}
else{
p=p->next;
}
}
dummynode = dummynode->next;
return dummynode;
}
};