码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode - Remove Linked List Elements

时间:2015-04-30 15:44:33      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:

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 };

 

LeetCode - Remove Linked List Elements

标签:

原文地址:http://www.cnblogs.com/zhuli19901106/p/4468946.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!