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

        while(*pp){
            if((*pp)->val == val){
                *pp = (*pp)->next;
            }else
                pp = &((*pp)->next);
        }
        return head;
    }
};

递归的方法 ```c++ /**

  • 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)   return head;
     int value = head->val;
    
     if(value == val){
         return removeElements(head->next, val);
     }else{
         head->next = removeElements(head->next, val);
         return head;
     }
    

    } }; ···

results matching ""

    No results matching ""