Remove Linked List Elements

 1 class Solution {
 2 public:
 3     ListNode* removeElements(ListNode* head, int val) {
 4         ListNode*cur,*nxt,*pre=head;
 5         if(head==NULL)
 6             return head;
 7         for(cur=head->next;cur!=NULL;cur=nxt)
 8         {
 9             nxt=cur->next;
10             if(cur->val==val)
11             {
12                 pre->next=nxt;
13                 free(cur);
14             }
15             else
16                 pre=cur;
17         }
18         if(head->val==val)
19         {
20             cur=head;
21             head=head->next;
22             free(cur);
23         }
24         return head;
25     }
26 };
View Code

做链表题如果 条件允许,最好手工模拟一遍,在做这道题的时候因为忘记写了一句pre=cur,一直出错。

完整代码:

 1 #include <iostream>
 2 #include <string>
 3 #include <vector>
 4 #include <algorithm>
 5 #include <cstring>
 6 #include <map>
 7 #include <cctype>
 8 #include <cmath>
 9 using namespace std;
10 
11 struct ListNode {
12     int val;
13     ListNode *next;
14     ListNode(int x) : val(x), next(NULL) {}
15 };
16 
17 class Solution {
18 public:
19     ListNode* removeElements(ListNode* head, int val) {
20         ListNode*cur,*nxt,*pre=head;
21         if(head==NULL)
22             return head;
23         for(cur=head->next;cur!=NULL;cur=nxt)
24         {
25             nxt=cur->next;
26             if(cur->val==val)
27             {
28                 pre->next=nxt;
29                 free(cur);
30             }
31             else
32                 pre=cur;
33         }
34         if(head->val==val)
35         {
36             cur=head;
37             head=head->next;
38             free(cur);
39         }
40         return head;
41     }
42 };
43 ListNode* ListInsert(int d)
44 {
45     ListNode *tmp;
46     tmp=(ListNode*)malloc(sizeof(ListNode));
47     tmp->val=d;
48     tmp->next=NULL;
49     return tmp;
50 }
51 int main()
52 {
53     int n,val;
54     while(cin>>n>>val)
55     {
56         ListNode *head,*tail,*cur;
57         tail=(ListNode*)malloc(sizeof(ListNode));
58         int i,d;
59         for(i=0;i<n;i++)
60         {
61             cin>>d;
62             cur=ListInsert(d);
63             if(i==0)
64             {
65                 head=cur;
66                 tail=head;
67             }
68             else
69             {
70                 tail->next=cur;
71                 tail=cur;
72             }
73         }
74         Solution sol;
75         ListNode *h=sol.removeElements(head,val);
76         for(;h!=NULL;h=h->next)
77             cout<<h->val<<" ";
78         cout<<endl;
79     }
80     return 0;
81 }
View Code

 

posted @ 2015-06-09 19:27  varcom  阅读(120)  评论(0编辑  收藏  举报