单向链表的头删

链表的头删分为空链表和非空链表两种情况,对于空链表,链表中一个节点都没有,所以无法删除,返回null,对于非空链表,头删就是让head(头节点)指向head的下一个节点,这样原来的头节点就被删除,此时head指向的节点就是删除原来头节点之后的头节点,直接返回现在的head即可。

public class Node {
    int  val;
    Node  next=null;
    Node(int  val){
        this.val=val;
    }
}

public class PopFront {//链表的头删
    public  static  Node popFront(Node  head){
      //空链表
      if(head==null){
          System.out.println("空链表无法删除");
          return  null;
      }
      //走到这里说明链表非空
        head=head.next;//直接将head指向head的下一个
         return head;
    }
    public static  void  Print(Node  head){
        Node  cur=head;
        while(cur!=null){
            System.out.print(cur.val+"-->");
            cur=cur.next;
        }
    }
    public  static  void  main(String[]  args){
        Node l1=new  Node(1);
        Node l2=new  Node(2);
        Node l3=new  Node(3);
        Node l4=new  Node(4);
        Node l5=new  Node(5);
        l1.next=l2;
        l2.next=l3;
        l3.next=l4;
        l4.next=l5;
        l5.next=null;
        System.out.print("头删前:");
        Print(l1);
        System.out.println("null");
        System.out.print("头删后:");
        Print(popFront(l1));
        System.out.println("null");
    }
}

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值