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

LeetCode 203. Remove Linked List Elements

时间:2018-01-11 23:50:37      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:target   blog   code   case   引入   hat   turn   情况   lin   

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

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

 

要求删除给定数值的节点,题目不难,老方法,引入虚拟头结点避免使用二重指针,遍历是一定要考虑指针为空的情况,否则不要去访问其next域,最后记得释放节点

代码如下:

 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         ListNode *dummy = new ListNode(-1), *pre = dummy;
13         dummy->next = head;
14         while (pre)
15         {
16             if (pre->next && pre->next->val == val)
17             {
18                 ListNode *t = pre->next;
19                 pre->next = t->next;
20                 delete t;
21             }
22             else
23                 pre = pre->next;
24         }
25         return dummy->next;
26         
27     }
28 };

时间复杂度:O(N)

空间复杂度:O(1)

 

参考:https://leetcode.com/problems/remove-linked-list-elements/discuss/57308/

LeetCode 203. Remove Linked List Elements

标签:target   blog   code   case   引入   hat   turn   情况   lin   

原文地址:https://www.cnblogs.com/dapeng-bupt/p/8270695.html

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