[LeetCode]203. Remove Linked List Elements
题目描述
思路
考虑头结点需要删除的情况
代码
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
while (head && head->val == val)
head = head->next;
ListNode* cur = head;
while (cur && cur->next) {
if (cur->next->val == val)
cur->next = cur->next->next;
else
cur = cur->next;
}
return head;
}
};
int main() {
ListNode* l1 = new ListNode(1);
ListNode* l2 = new ListNode(6);
ListNode* l3 = new ListNode(2);
ListNode* l4 = new ListNode(6);
ListNode* l5 = new ListNode(6);
l1->next = l2;
l2->next = l3;
l3->next = l4;
l4->next = l5;
Solution s;
ListNode* res = s.removeElements(l1, 6);
while (res) {
cout << res->val << " ";
res = res->next;
}
cout << endl;
system("pause");
return 0;
}
本文介绍了 LeetCode 上第 203 题 移除链表元素 的解题思路及 C++ 实现。通过迭代的方式遍历链表,删除指定值的所有节点,并考虑到头结点可能被删除的情况。
740

被折叠的 条评论
为什么被折叠?



