Leetcode: Remove Linked List Elements
来源:互联网 发布:sql 用变量作为字段名 编辑:程序博客网 时间:2024/06/05 09:32
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
简单。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode* removeElements(ListNode* head, int val) { while (head != nullptr && head->val == val) { head = head->next; } if (head == nullptr) { return head; } ListNode* prev = head; ListNode* cur = head->next; while (cur != nullptr) { if (cur->val != val) { prev->next = cur; prev = cur; } cur = cur->next; } prev->next = nullptr; return head; }};
Hack的方法,直接移动值。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode* removeElements(ListNode* head, int val) { ListNode* cur = head; ListNode* prev = head; ListNode* tail = nullptr; while (cur != nullptr) { if (cur->val != val) { prev->val = cur->val; tail = prev; prev = prev->next; } cur = cur->next; } if (tail != nullptr) { tail->next = nullptr; } else { head = nullptr; } return head; }};
0 0
- [LeetCode] Remove Linked List Elements
- [LeetCode]Remove Linked List Elements
- Leetcode--Remove Linked List Elements
- [LeetCode]Remove Linked List Elements
- leetcode Remove Linked List Elements
- [LeetCode] Remove Linked List Elements
- [leetcode]Remove Linked List Elements
- leetcode--Remove Linked List Elements
- [LeetCode] Remove Linked List Elements
- 【leetcode】Remove Linked List Elements
- LeetCode:Remove Linked List Elements
- [leetcode]Remove Linked List Elements
- Remove Linked List Elements [leetcode]
- LeetCode: Remove Linked List Elements
- LeetCode Remove Linked List Elements
- [Leetcode]Remove Linked List Elements
- LeetCode Remove Linked List Elements
- Remove Linked List Elements -- leetcode
- 网页设计的几大趋势
- 【Mac版】串口开发搭建环境步骤
- Leap Motion的环境配置(使用c#)
- java内部类学习笔记
- 深度优先搜索(Depth-First-Search)
- Leetcode: Remove Linked List Elements
- linux常用命令二之权限,搜索与帮助命令
- IIS下安装PHP
- Android APK安装常见错误列表
- 链表操作
- [ios]the file couldn't be opened because you don't have permission to view it
- 格雷码 Gray
- nginx源码分析1———进程间的通信机制五(文件锁)
- 通过Mesos、Docker和Go,使用300行代码创建一个分布式系统