问题描述:
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
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
分析:注意链表的头部即可。
代码如下:8ms
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeElements(struct ListNode* head, int val) {
if(!head)
return head;
struct ListNode* tmpNode=head;
struct ListNode* prevNode = NULL;
while(tmpNode){
if(tmpNode->val==val){
if(!prevNode){
head = tmpNode->next;
}else{
prevNode->next = tmpNode->next;
}
}else{
prevNode = tmpNode;
}
tmpNode = tmpNode->next;
}
return head;
}