首页 > 其他 > 详细

LeetCode - Remove Linked List Elements

时间:2015-04-30 15:43:23      阅读:168      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!