小小程序媛  
得之坦然,失之淡然,顺其自然,争其必然

题目

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.

分析

删除链表中的指定值的节点。

需要注意的是,所需要删除节点的位置,头,中间,尾,不同位置需要不同处理,避免断链~

AC代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */

class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        if (head == NULL)
            return head;

        ListNode *pre = head, *p = head;
        while (p)
        {
            //找到要删除的节点元素
            if (p->val == val)
            {
                //判断当前节点为头结点
                if (p == head)
                {
                    head = p->next;
                    ListNode *q = p;
                    //更新头
                    p = head;
                    pre = head;
                    delete q;
                    q = NULL;
                }
                //删除尾节点
                else if (p->next == NULL)
                {
                    pre->next = NULL;               
                    delete p;
                    p = NULL;
                }
                //删除链表中间节点
                else{
                    pre->next = p->next;

                    ListNode *q = p;
                    p = p->next;
                    delete q;
                    q = NULL;
                }//else
            }//if
            else{
                pre = p;
                p = p->next;
            }

        }//while
        return head;
    }
};

GitHub测试程序源码

posted on 2015-11-03 13:23  Coding菌  阅读(109)  评论(0编辑  收藏  举报