删除链表中等于给定值 val 的所有节点。
示例:
输入: 1->2->6->3->4->5->6, val = 6 输出: 1->2->3->4->5
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode *trick = new ListNode(0);
trick ->next = head;
ListNode *currentNode = head;
ListNode *lastNode = trick;
while(currentNode != NULL)
{
if(currentNode ->val == val)
{
lastNode ->next = currentNode ->next;
currentNode = currentNode ->next;
}
else
{
lastNode = currentNode;
currentNode = currentNode ->next;
}
}
return trick ->next;
}
};
本文介绍了一种在链表中删除所有等于给定值节点的方法。通过使用虚拟头节点简化边界条件,遍历链表并调整指针指向,实现高效删除操作。
1202

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



