您的位置:首页 > 其它

[LeetCode]203. Remove Linked List Elements

2016-09-05 23:14 176 查看
203. Remove Linked List ElementsRemove 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
删除链表中指定的所有元素。1)删除链表节点时应及时释放节点内存,以免内存泄漏。
2)如果节点值和给定值一致便删除,给*list赋值下个节点;否则取下一节点即可。
/**
* 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 **list = &head;
while ( *list )
{
if ( (*list)->val == val )
{
struct ListNode *delete = *list;
*list = (*list)->next;
free(delete);
}
else
{
list = &(*list)->next;
}
}
return head;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Code Leet