[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

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

 

Subscribe to see which companies asked this question

Solution:
 
 1 struct ListNode* removeElements(struct ListNode* head, int val) 
 2 {
 3     struct ListNode dummy;
 4     struct ListNode* p = &dummy;
 5     dummy.next = head;
 6         
 7     while (p->next != NULL)
 8     {
 9         if (p->next->val == val) // find, delete it
10         {
11             p->next = p->next->next;
12         }
13         else // go on
14         {
15             p = p->next;
16         }
17     }
18     
19     return dummy.next;
20 }

 

你可能感兴趣的:([leetcode 203] Remove Linked List Elements)