Skip to content

Instantly share code, notes, and snippets.

@superlayone
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save superlayone/2d1f4a09f775eff01fc4 to your computer and use it in GitHub Desktop.
Save superlayone/2d1f4a09f775eff01fc4 to your computer and use it in GitHub Desktop.
Pointer to pointer

###Pointer to pointer

在删除链表的节点的时候,需要考虑是否删除的是头节点的问题,要保存前驱结点的信息,今天看到了一个巧妙地用法,利用二级指针

Code

    /*
    struct ListNode{
    	int val;
    	ListNode* next;
    	ListNode(int v):val(v),next(nullptr){}
    };
    */
    typedef bool (* remove_fn)(const ListNode* node,int val);
    
    bool rm(const ListNode* node,int val){
    	if(node->val == val){
    		return true;
    	}
    	return false;
    }
    void remove_if(ListNode** head,remove_fn rm,int target){
    	ListNode** cur = head;
    
    	for(; *cur;){
    		ListNode* entry = *cur;
    		if(rm(entry,target)){
    			*cur = entry->next;
    			delete entry;
    		}else{
    			cur = &(entry->next);
    		}
    	}
    }

此处输入图片的描述

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment