Leetcode题目: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

题目解答:

这个题目非常简单,就是来删除在链表中出现的值为val的节点,并返回删除之后的链表。

1,为链表增加一个虚拟的头结点,从而减少了很多冗余的判断条件,十分简单。

2,代码结束时,需要注意将自己申请的那个虚拟头结点的空间释放掉。

代码:

/**
 * 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) {
        ListNode *Head = new ListNode(-1);
        Head -> next = head;
        ListNode *p = Head;
        ListNode *q = Head -> next;
        while(q != NULL)
        {
            while((q != NULL) && (q -> val != val))
            {
                p = p -> next;
                q = q -> next;
            }
            if(q == NULL)
            {
                break;
            }
            if(q -> val == val)
            {
                ListNode *r = q ->next;
                p -> next = r;
                delete q;
                q = r;
            }
        }
        p = Head -> next;
        delete Head;
        return p;
    }
};

posted @ 2016-04-20 19:15  CodingGirl121  阅读(98)  评论(0编辑  收藏  举报