Leetcode: Remove Linked List Elements
2015-08-04 23:53
381 查看
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
简单。
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;
}
};
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;
}
};
相关文章推荐
- [C/C++]反转链表
- C#实现基于链表的内存记事本实例
- C语言实现带头结点的链表的创建、查找、插入、删除操作
- C++实现简单的学生管理系统
- Linux内核链表实现过程
- C++链表倒序实现方法
- C#通过链表实现队列的方法
- 找出链表倒数第n个节点元素的二个方法
- Java数据结构之简单链表的定义与实现方法示例
- C语言单循环链表的表示与实现实例详解
- C++实现的链表类实例
- PHP小教程之实现链表
- C语言双向链表的表示与实现实例详解
- C语言实现输出链表中倒数第k个节点
- C++语言实现线性表之链表实例
- STL list链表的用法详细解析
- C语言创建链表错误之通过指针参数申请动态内存实例分析
- php链表用法实例分析
- JavaScript中数据结构与算法(三):链表
- 编码实现从无序链表中移除重复项(C和JAVA实例)