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
解析:
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* newhead = new ListNode(-1);
newhead->next = head;
ListNode* pre = newhead;
ListNode* cur = head;
while(cur != NULL)
{
if(cur->val == val)
{
cur = cur->next;
pre->next = cur;
}
else
{
pre = cur;
cur = cur->next;
}
}
return newhead->next;
}
};
方法二:
void removeHelper(ListNode *&head, int val)
{
if (head == nullptr)
{
return;
}
else if (head->val == val)
{
head = head->next;
}
else
{
removeHelper(head->next, val);
}
}
方法三(有问题一直不能AC):
/**
* 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) {
if (!head)
return NULL;
if (head->next == NULL)
return head;
ListNode *p = head->next;
ListNode *pre = head;
while (p)
{
if (p->val == val)
{
ListNode *r = p->next;
pre->next = r;
free(p);
p = r;
}
else
{
pre = p;
p = p->next;
}
}
return head;
}
};
方法四:
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode *p = head;
ListNode *pre = head;
while (p)
{
if (p->val == val)
{
if(p==head)
pre = head = p->next;
else
pre->next = p->next;
free(p);
p = pre;
}
else
{
pre = p;
p = p->next;
}
}
return head;
}
};