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

 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     ListNode* removeElements(ListNode* head, int val) {
12         if(head==NULL)
13             return head;
14         else
15         {  
16             while(head&&head->val==val)
17             {
18                 head=head->next;
19             }
20         }
21         ListNode *p = head;
22         ListNode *p1;
23         while (p)
24             {
25                 if (p->val == val)
26                 {
27                     p = p->next;
28                     p1->next=p;
29                 }
30                 else
31                 {
32                     p1 = p;
33                     p = p->next;    
34                 }
35             }
36         
37         return head;
38     }
39 };

 

posted on 2017-07-06 15:42  无惧风云  阅读(129)  评论(0编辑  收藏  举报