删除链表最后尾节点(1319 P103)

问题:删除一个链表最后一个节点,只知道首节点first.

思路:因为只知道首节点,所以只能历遍链表,找到最后两个节点,将倒数第二个节点的next定义为null,无法关联最后一个节点,就可以实现。(之所以不直接让最后一个为空,是为了保证准确性)

代码:
package chapter1.a3 ;

public class Example1319 {

private class Node{
int item ;
Node next ;
}

private Node first ;

private void deleteLastNode(){
Node current = first ;
if (current == null) return;

Node next = current. next ; //如果next为空,那么就只有一个first存在,所以直接first为空就可以了
if (next == null)
first = null;

while (next. next != null){
current = next ;
next = next. next ;
}

current. next = null; // 这里为什么不能够直接写 next = null;
// 因为next = null 并不意味着 current 访问不到 current.next,还是可以的,
// 所以要写为 current.next = null, 这样才能保证删除最后一个节点

}

}
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值