
//注意链表为空的情况
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
while (head != NULL && head->val == val) {
ListNode* temp = head;
head = head->next;
delete temp;
}
if (head == NULL) return head;
ListNode* curNode = head;
while (curNode->next != NULL) {
if (curNode->next->val != val) {
curNode = curNode->next;
}
else {
ListNode* temp = curNode->next;
curNode->next = curNode->next->next;
delete temp;
}
}
return head;
}
};
int main()
{
Solution sol;
vector<int> input1 = {7,7,7,7,7,2,4,3,1,1,2,3,7};
ListNode *head = createListNode(input1);
int x = 7;
printLinkedList(sol.removeElements(head, x));
return 0;
}

本文介绍了一种链表中特定元素的移除算法,通过迭代检查和删除操作,实现链表的有效清理。代码示例展示了如何从链表头部开始,逐个节点检查并删除指定值的所有实例。
851

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



