Remove Linked List Elements

2015.4.30 15:00

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

Solution:

  Watch out for boundary cases.

Accepted code:

 1 // 1AC, no surprise
 2 /**
 3  * Definition for singly-linked list.
 4  * struct ListNode {
 5  *     int val;
 6  *     ListNode *next;
 7  *     ListNode(int x) : val(x), next(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     ListNode* removeElements(ListNode* head, int val) {
13         ListNode *ptr;
14         
15         while (head != NULL && head->val == val) {
16             ptr = head;
17             head = head->next;
18             delete ptr;
19         }
20         
21         ListNode *head0 = head;
22         
23         if (head0 == NULL) {
24             return NULL;
25         }
26         
27         while (head->next != NULL) {
28             if (head->next->val == val) {
29                 ptr = head->next;
30                 head->next = ptr->next;
31                 delete ptr;
32             } else {
33                 head = head->next;
34             }
35         }
36         
37         return head0;
38     }
39 };

 

 posted on 2015-04-30 15:04  zhuli19901106  阅读(412)  评论(0编辑  收藏  举报