前言
1、暴力解法。遍历链表
2、待优化。
题目
删除链表中等于给定值 val 的所有节点。
示例:
输入: 1->2->6->3->4->5->6, val = 6
输出: 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) return NULL;
while(head && head->val==val)
head=head->next;
if(!head) return NULL;
ListNode *p=head;
while(p->next){
if(p->next->val==val)
p->next=p->next->next;
else p=p->next;
}
return head;
}
};