6、移除链表元素

方法1:原链表删除元素

 伪代码:

        首先判断头节点是否是待删除元素。(头节点和其他节点的删除方法不一样)

while(head != null && head->value == target)
//如果链表为 1 1 1 1 1,要删除元素1时用if就会失效
{
    head = head->next;
}
cur = head;
//为什么不是从head->next开始
//因为不方便删除链表节点,如果指向head->next的话,head会丢失,不方便删除链表节点
while(cur != null && cur ->next != null)
{
    if(cur->next->value == target)
    {
        cur->next = cur->next->next;
    }
    else
    {
        cur = cur->next;
    }
}
return head;

方法2:虚拟头节点

        增加一个虚拟头节点,如果删除的是头节点,那么直接删除就行。

伪代码:

dumyhead = new();//创建虚拟头节点
dumyhead->next = head;
cur = dumy->head;
while(cur->next != null)
{
    if(cur->next->value = target)
        cur->next = cur->next->next;
    else
        cur = cur->next;
}
return dumyhead->next;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值