求:spa
刪除鏈表中等於給定值 val 的全部節點。rem
示例:it
輸入: 1->2->6->3->4->5->6, val = 6
輸出: 1->2->3->4->5
解:io
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct
ListNode* removeElements(
struct
ListNode* head,
int
val){
if
(head==NULL)
return
head;
struct
ListNode* pre = (
struct
ListNode*)malloc(
sizeof
(
struct
ListNode));
pre->next = head;
struct
ListNode* tmp = pre;
while
(tmp->next!=NULL){
if
(tmp->next->val == val){
struct
ListNode* delNode = tmp->next;
tmp->next = tmp->next->next;
free(delNode);
}
else
{
tmp=tmp->next;
}
}
return
pre->next;
}