首页 > 其他 > 详细

[LeetCode]203. Remove Linked List Elements

时间:2016-09-06 01:15:11      阅读:154      评论:0      收藏:0      [点我收藏+]

203. Remove Linked List Elements

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


删除链表中指定的所有元素。

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;
}


[LeetCode]203. Remove Linked List Elements

原文:http://11998200.blog.51cto.com/11988200/1846598

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!