leetcode 203

struct ListNode* removeElements(struct ListNode* head, int val) 
{
    struct ListNode * tmp = (struct  ListNode *)malloc(sizeof(struct ListNode));
    struct ListNode * pre = tmp;
    pre->next = head;
    while(head != NULL)
    { 
        if(head->val == val) { 
            head= head->next;
            pre->next = head;
        }else{
            head = head->next;
            pre = pre->next;
        } 
    } 
    return tmp->next;
}

基本思路:

在删某个节点的时候需要修改该节点前面节点的next指针,所以需要有一个pre指针

另外需要有个节点来保存节点最初的位置 。

struct ListNode* removeElements(struct ListNode* head, int val)
{
    struct ListNode * tmp = (struct  ListNode *)malloc(sizeof(struct ListNode));
    struct ListNode * pre = tmp;
    pre->next = head;
    while(head != NULL)
    {
        if(head->val == val) {
            head= head->next;
            pre->next = head;
        }else{
            head = head->next;
            pre = pre->next;
        }
    }
    return tmp->next;
}

posted on 2016-01-27 21:58  追寻前人的脚步  阅读(376)  评论(0编辑  收藏  举报

导航