[LeetCode] 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

问题:给定列表表头,删除列表中值为 val 的元素。

比较方便的方法是,每次比较 p->next->val 与 val ,当相等时跳过 p->next 即可: p->next = p->next->next;

 1     ListNode* removeElements(ListNode* head, int val) {
 2         
 3         ListNode* p = new ListNode(0);
 4         p->next = head;
 5         
 6         ListNode* pMake = p;
 7         
 8         while(p->next != NULL){
 9             if (p->next->val == val){
10                 p->next = p->next->next;
11             }else{
12                 p = p->next;
13             }
14         }
15         head = pMake->next;
16         
17         return head;
18     }
原文地址:https://www.cnblogs.com/TonyYPZhang/p/5090492.html