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

 

 

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
 
 /*
 解题思路:
 要分为val 在头,在尾,在链表中间
 新建一个头结点,使得链表有以一个空节点为头,然后只需要考虑链表中间和链表尾部的两种情况
 
 */
 
class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        if(head == NULL)
            return head;
        
        ListNode* tempHead = new ListNode(0);
        tempHead->next = head;
        ListNode* pre = tempHead;
        ListNode* cur = head;
        
        while(cur){
            if(cur->val == val && cur->next != NULL){
                ListNode* ptr = cur;
                cur = cur->next;
                pre->next = ptr->next;
                free(ptr);
            }
            else if(cur->val == val && cur->next == NULL){
                cur = cur->next;
                pre->next = cur;
            }
            else {
                pre = pre->next;
                cur = cur->next;
            }
    
        }
        
        return tempHead->next;
    }
};

 

posted on 2015-08-30 11:21  horizon.qiang  阅读(347)  评论(0编辑  收藏  举报

导航