Friday, May 15, 2015

203 Remove Linked List Elements

来源:Leetcode

原帖:https://leetcode.com/problems/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 dummy(0);  
     dummy.next = head;  
     ListNode* cur = &dummy;  
     while (cur->next) {  
       if (cur->next->val == val) {  
         ListNode* del = cur->next;  
         cur->next = cur->next->next;  
         delete del;  
       } else {  
         cur = cur->next;  
       }  
     }  
     return dummy.next;  
   }  
 };  

No comments:

Post a Comment