Remove Linked List Elements

题目大致题意就是:给定一个链表头节点和一个数值,删除链表结点中所有数值等于该给定数值的结点!!

 1 class Solution {
 2 public:
 3     ListNode* removeElements(ListNode* head, int val) {
 4         ListNode node(-1);
 5         node.next = head;
 6         ListNode *ptr = &node;
 7         while (ptr)//不要写成while(ptr->next!=NULL)关键点1
 8         {
 9             if (ptr->next && ptr->next->val == val)
10             {
11                 //ListNode *temp = ptr->next;
12                 ptr->next = ptr->next->next;
13                 //free(temp);
14             }
15             else//不能丢!!关键点2
16             ptr = ptr->next;
17         }
18         return node.next;
19     }
20 };

 leetcode讨论区的一大神的代码(为什么要利用指针的指针呢??)

 1 ListNode *removeElements(ListNode *head, int val)
 2 {
 3     ListNode **list = &head;
 4 
 5     while (*list != nullptr)
 6     {
 7         if ((*list)->val == val)
 8         {
 9             *list = (*list)->next;
10         }
11         else
12         {
13             list = &(*list)->next;
14         }
15     }
16 
17     return head;
18 }

 大神的这段代码,关键就在于对   *list=(*list)->next 的理解:

  其效果就是删除了当前list间接指向的结点!这儿不好编辑图片,总之,(*list)就是当前list间接指向的结点的前一结点的next,能理解到这一点就好办了!

  

手里拿着一把锤子,看什么都像钉子,编程界的锤子应该就是算法了吧!
原文地址:https://www.cnblogs.com/chess/p/4871915.html