手把手带你学会操作链表 | LeetCode:203.移除链表元素_哔哩哔哩_bilibili
原始代码
思路:开辟一个新链表
cur=head,cur去遍历原链表。
如果cur!=val,就把值给给新链表。 最后新链表里面就是没有重复值的链表,返回新链表头节点即可。
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
if(head==nullptr)return head;
ListNode* ret=new ListNode;
ret=head;
ListNode* cur=head;
if(cur==nullptr)return cur;
while(cur)
{
cur=cur->next;
if(cur->val!=val)
{
ret->next=cur;
}
}
return ret;
}
};
错误原因:
In the line `ListNode* ret=new ListNode;`, you need to provide an argument to the `ListNode` constructor, as it expects an integer value for the node's `val` field. You can provide a default value of `0` if you don't have a specific value to assign
修改之后: ListNode* ret=new ListNode(0);
原链表删除
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
//链表:1 1 1 1 1 1 1 ,var=1 的情况
while(head!=nullptr&&head->val==val)
{
head=head->next;
}
//其他情况
ListNode* cur=head;
while(cur!=nullptr && cur->next!=nullptr)
{
if(cur->next->val==val)
{
cur->next=cur->next->next;
}
else
{
cur=cur->next;
}
}
return head;
}
};
虚拟头节点
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
//if(head==nullptr)return head;
ListNode* dummy=new ListNode(0);
dummy->next = head;
ListNode* pre =dummy;
ListNode* cur=head;
//假设数组为 【1,2,3,4】 val=1
// pre cur
while(cur)
{
if(cur->val==val) //值如果相等
{
//就把这个数跳过
pre->next=cur->next; //pre->2
delete cur; //删掉1
//数组变为【2,3,4】
// pre cur
cur=pre->next; //cur=3
}
else //否则 假设数组=【1,2,3】 val=2
{ // pre cur
//cur的值不等于val
pre=cur; //把pre给给cur,cur到下个节点
cur= cur->next; //【1,2,3】
// pre cur
}
}
return dummy->next;
//总结 :快慢指针 后指针如果和val等,就把前指针链后指针下个节点。
//不相等就交换前后指针,再让交换完了的后指针接着往下走
}
};