删除链表中等于给定值 val 的所有节点。
示例:
输入: 1->2->6->3->4->5->6, val = 6 输出: 1->2->3->4->5
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode cur = new ListNode(-1);
ListNode p = cur;
while(head != null){
if(head.val == val){
cur.next = head.next;
}else{
cur.next = head;
cur = cur.next;
}
head = head.next;
}
return p.next;
}
}
/**
* 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;
ListNode FirstNode(0);
FirstNode.next = head;
ListNode *p = &FirstNode;
while(p != NULL){
ListNode *tmp = p->next;
if(tmp != NULL&&tmp->val == val)
{
p->next = tmp->next;
delete tmp;
}else
p = p->next;
}
return FirstNode.next;
}
};