abc_begin

导航

452. Remove Linked List Elements【Naive】

Remove all elements from a linked list of integers that have value val.

Example

Given 1->2->3->3->4->5->3, val = 3, you should return the list as 1->2->4->5

 

解法一:

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     /**
12      * @param head a ListNode
13      * @param val an integer
14      * @return a ListNode
15      */
16     ListNode *removeElements(ListNode *head, int val) {
17         ListNode * dummy = new ListNode(-1);
18         dummy->next = head;
19         head = dummy;
20         
21         while (head->next != NULL) {
22             if (head->next->val == val) {
23                 head->next = head->next->next;
24                 continue;
25             }
26             
27             head = head->next;
28         }
29         
30         return dummy->next;
31     }
32 };

 

posted on 2018-02-03 14:56  LastBattle  阅读(127)  评论(0编辑  收藏  举报