您的位置:首页 > 其它

[Leetcode 203, Easy] Remove Linked List Elements

2015-05-04 10:34 197 查看
Problem:

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
Analysis:

Solutions:

C++:

ListNode* removeElements(ListNode* head, int val) {
        if(head == NULL)
            return head;
            
        while(head != NULL && head->val == val) {
            ListNode *temp = head;
            head = head->next;
            temp->next = NULL;
        }
            
        if(head == NULL)
            return head;

        ListNode *front = head->next;
        ListNode *back = head;
        while(front != NULL) {
            if(front->val == val) {
                ListNode *temp = front;
                back->next = front->next;
                front = front->next;
                temp->next = NULL;
            } else {
                back = front;
                front = front->next;
            }
        }

        return head;
    }
Java:

Python:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: