链表经典问题之删除链表元素专题笔记

链表经典问题之删除链表元素专题笔记

leetcode203. 移除链表元素

解题思路 1。创建一个虚拟表头dummy,dummy->next=head
2.遍历链表元素,寻找目标元素,使用cur->next->val来判断
3.找到目标元素,使用cur->next=cur->next->next;
4,最后要返回dummy->next

struct ListNode* removeElements(struct ListNode* head, int val)
{
    struct ListNode* dummyHead=(struct ListNode*)malloc(sizeof(struct ListNode));
    dummyHead->next=head;
    //dummyHead->val = 0;
    struct ListNode* cur = dummyHead;
    while(cur->next!=NULL)
    {
        if(cur->next->val==val)
        {
            cur->next=cur->next->next;
        }
        else
        {
            cur=cur->next;
        }
    }
    return dummyHead->next;
}

leetcode19.删除倒数第n个结点

解题思路
1.遍历链表,得出链表总长度L,L-N+1就是我们要删除的元素,
注意链表从0开始标号的(比如0.1.2.3)

int getlength(struct ListNode*p)
{
    int length=0;
    while(p!=NULL)
    {
        length++;
        p=p->next;
    }
    return length;
}

struct ListNode* removeNthFromEnd(struct ListNode* head, int n)
{
    struct ListNode* dummy=(struct ListNode*)malloc(sizeof(struct ListNode));
    dummy->next=head;
    int length=getlength(head);
    struct ListNode* cur=dummy;
    for(int i=1;i<length-n+1;i++)
    {
        cur=cur->next;
    }
    cur->next=cur->next->next;
    return dummy->next;


}

删除重复元素

1.重复元素保留一个leetcode83

struct ListNode* deleteDuplicates(struct ListNode* head)
{
    struct ListNode* cur=(struct ListNode*)malloc(sizeof(struct ListNode));
    cur=head;
    if(head==NULL)
    {
        return head;
    }
    while(cur->next!=NULL)
    {
        if(cur->val==cur->next->val)
        {
            cur->next=cur->next->next;
            
        }
        else
        cur=cur->next;
    }
    return head;
}

== 2.重复元素都不要leetcode82==

struct ListNode* deleteDuplicates(struct ListNode* head){
    if(head==NULL)
    {
        return head;
    }
     struct ListNode* dummy=(struct ListNode*)malloc(sizeof(struct ListNode));
     dummy->val=0;
     dummy->next=head;
    struct ListNode* cur=(struct ListNode*)malloc(sizeof(struct ListNode));
    cur=dummy;
    while(cur->next!=NULL&& cur->next->next!=NULL)
    {
        if(cur->next->val==cur->next->next->val)
        {
            int x=cur->next->val;
            while(cur->next!=NULL && cur->next->val==x)
            {
                cur->next=cur->next->next;
            }
        }
        else
        cur=cur->next;
    }
    return dummy->next;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值