一、题目描述
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
题目描述:给一个链表和一个值val,删除链表中所有值等于val的节点
思路:分两种情况,(1)当删除的节点为头结点时,注意将head往后移动
(2)当删除的节点不是头结点时,正常删除即可。
最后返回head。
c++代码(32ms,64.27%)
/**
* 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) {
ListNode* pre;
pre->next=head;
ListNode* cur=head;
while(cur!=NULL){
if(cur->val == val){
if(cur == head)
head=cur->next;
pre->next=cur->next;
cur=pre->next;
}else{
pre=cur;
cur=cur->next;
}
}
return head;
}
};