leetcode 原题链接:https://leetcode.com/problems/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
需要注意的是,删除的点在链表头与表身需要分开处理。
实现代码:
/**
* 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 == NULL)
return NULL;*/
while (head != NULL && head->val == val)
{
ListNode *temp = head;
head = head->next;
/*delete temp;
temp = NULL;*/
}
if (head == NULL)
{
return NULL;
} else
{
ListNode *pre = head;
ListNode *cur = head;
while (cur != NULL)
{
if (cur->val == val)
{
ListNode *temp = cur;
pre->next = cur->next;
cur = cur->next;
/*delete temp;
temp = NULL;*/
} else
{
pre = cur;
cur = cur->next;
}
}
}
return head;
}
};