删除链表中等于给定值 val 的所有节点。

这道题的做法是遍历列表,定义一个当前结点的前驱,当前结点,当碰到和该数据相同的数,就让改数据所在结点的前驱指向当前结点的下一个结点,如果不相同,前驱和当前结点继续遍历,重复此操作,还有一种特殊情况就是当要删除的结点的数据和头结点相同时要分开处理。
有三种解决办法,第一种是直接把头结点移至下一个结点,代码如下:

  public Node removeElements(Node head, int val)
	  {
		  Node pre=null;
		  Node cur=head;
		  while(cur!=null)
		  {
			  if(cur.val==val)
			  {
				  if(cur==head)
				  {
					  head=cur.next;
				  }
				  pre.next=cur.next;
			  }else
			  {
				  pre=cur;
			  }
			  cur=cur.next;
		  }
		  return head;
	  }

第二种是先遍历,遍历完之后对头结点在进行判断

 public Node removeElements(Node head, int val){
 if(head==null)
		  {
			  return null;
		  }
		 
		  Node pre=head;
		  Node cur=head.next;
		  while(cur!=null)
		  {
			  if(cur.val==val)
			  {
				  pre.next=cur.next;
			  }
			  else
			  {
				  pre=cur;
			  }
			  cur=cur.next;
		  }
			  if(head.val==val)
			  {
				  head=head.next;        
			  }
			 
		  
		  return head;	
	  }
		  

第三种是强行给头结点找一个值不为空的前驱,然后返回这个前驱的下一个结点

 public Node removeElements(Node head, int val){
 	  Node newHead=new Node(2);//这个值可以是任意数值
 	  newHead.next=head;
	  Node pre=newHead;
	  Node cur=head;
	  while(cur!=null)
	  {
		  if(cur.val==val)
		  {
			  pre.next=cur.next;
		  }
		  else
		  {
			  pre=cur;
		  }
		  cur=cur.next;
	  }
	  return newHead.next;
	  
	  
  }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值