删除链表中所有值为val的结点

  1. 新建一个链表将所有值不是val的结点进行尾插操作
class Solution {
    public ListNode removeElements(ListNode head, int val) {
        ListNode result = null;
        ListNode cur = head;
		ListNode last=null;//用来记录当前链表的最后一个结点
        while (cur != null) {
            if (cur.val == val) {
                cur=cur.next;
                continue;//结束本次循环
            }
            else
            {
				ListNode next=cur.next;
				cur.next=null;
				if(result==null){//进行尾插时考虑链表是否为空
					result=cur;
				}
				else{
					last=last.next;//查找最后一个结点
				}
				last=cur;
				cur=next;
			}
		}
			return result;
	}
}

2.设置两个引用,并对第一个结点做特殊处理

class Solution {
    public ListNode removeElements(ListNode head, int val) {
         ListNode prev = null;//始终指向cur的前驱结点
        ListNode cur = head;
        
        while (cur != null) 
	{
            if (cur.val == val) {
                if (cur == head) {
                    head = cur.next;
		    cur = cur.next;//对头结点进行处理,防止要删除的结点出现在第一个位置
                } else {
                    prev.next = cur.next;//若不对头结点进行处理,prev会报错
		    cur = cur.next;
		}
            } 
	    else {
	      prev = cur;
	      cur = cur.next;
           }
        }
        
        return head;
    }
}

3.设置两个引用,跳过第一个节点最后处理

class Solution {
    public ListNode removeElements(ListNode head, int val) {
         ListNode prev = null;
        ListNode cur = head;
        
        while (cur != null) 
	{
            if (cur.val == val) 
              {
                    prev.next = cur.next;
		    cur = cur.next;
		}
                else 
		{
		        prev = cur;
			cur = cur.next;
                }
        }
        if(head.val==val)
             head=head.next;

        
        return head;
    }
}//对头结点进行最后处理

4.设置两个引用,并强行加一个前驱结点

class Solution {
	public ListNode removeElements(ListNode head, int val) {

        ListNode tmpHead = new ListNode(-1);//强行加一个前驱结点

        tmpHead.next = head;

        ListNode prev = tmpHead;

        ListNode cur = head;

        while (cur != null) {

            if (cur.val == val) {

                prev.next = cur.next;

            } else {

                prev = cur;

            }
			cur = cur.next;
		}
	return tmpHead.next;
	}
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值