删除链表中等于给定值 val
的所有节点。
样例
样例 1:
输入:head = 1->2->3->3->4->5->3->null, val = 3
输出:1->2->4->5->null
样例 2:
输入:head = 1->1->null, val = 1
输出:null
/**
* Definition of singly-linked-list:
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: a ListNode
* @param val: An integer
* @return: a ListNode
*/
ListNode * removeElements(ListNode * head, int val)
{
// write your code here
ListNode * ret = NULL;
ListNode * tail = NULL;
while(head)
{
ListNode * next = head->next;
if(head->val != val)
{
if(ret == NULL)
{
ret = head;
tail = head;
tail->next = NULL;
}
else
{
tail->next = head;
tail = head;
tail->next = NULL;
}
}
head = next;
}
return ret;
}
};