问题描述:

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) {}
 * };
 */
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {

  }
};

翻译:

将单向链表中与所给val值相等的元素去掉。

例如:

所给输入值:1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6

返回值:1 --> 2 --> 3 --> 4 --> 5

解题思路:

分情况考虑,首先判断是否为空链表,若非空再判断此链表第一个元素是否需要被第二个替换掉,然后判断链表的下一个元素是否需要被替换掉,接下来就递归调用,对之后的节点重复的进行同样的判断。

/**
 * 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* temp;
        temp = head;
        if(!temp) return head;
        else
        {
            if(temp -> val != val)
            {
                head = temp;
                if(!temp -> next) return head;
                else if(temp -> next -> val == val)
                {
                    head -> next = temp -> next -> next;
                    head -> next = removeElements(head -> next, val);
                }
                else head -> next = removeElements(head -> next, val);
            }
            else if(temp -> val == val)
            {
                head = temp -> next;
                head = removeElements(head, val);
            }
        }
        return head;
    }
};