单链表面试题

这篇博客主要介绍了Java中单链表的几个核心操作,包括计算链表的有效节点数、查找倒数第k个节点以及实现链表的反转。这些是常见的面试题,涉及链表的基本特性和遍历技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

单链表的面试题

image-20221127214900597

  • 1.求单链表中的有效节点的个数
/**
     *
     * @param heroNode  链表的头结点
     * @return 返回的就是有效节点的个数
     */
    public static int getLength(HeroNode heroNode){
        if (heroNode.next == null){
            return 0;
        }
        int length = 0;
        HeroNode temp = heroNode.next;
        while (temp != null){
            length++;
            temp = temp.next; //遍历整个链表
        }
        
        return length;
    }
  • 2.查找单链表中的倒数第k个节点
/**
     * 查找单链表中的倒数第k个节点
     * @param index
     * @param heroNode
     * @return
     */
    public  static HeroNode getNodeByInedx(int index,HeroNode heroNode){
        if (heroNode.next == null){
            return  null;
        }
        int size = getLength(heroNode);
        //第二次遍历
        if(index < 0 || index >= size){
            return  null;
        }
        HeroNode temp = heroNode.next;
        for (int i = 0; i < size-index; i++) {
            temp = temp.next;
        }

        return temp;
    }
  • 3.单链表的反转

image-20221128104544566

/**
     * 链表反转
     * @param head
     */
    public static  void reverseSingleLinkedList(HeroNode head){
        if (head == null || head.next.next == null) {
            return;
        }
        HeroNode cur = head.next;
        HeroNode next = null;
        HeroNode reversHead = new HeroNode(0,"","");
        while (cur.next !=null){
            next = cur.next;
            cur.next = reversHead.next;
            cur = next;//后移

        }
        
        head.next  = reversHead.next ;
    }
  • 从头到尾打印链表

image-20221128104218521

/**
     * 逆序打印链表
     * @param head
     */
    public static void reversPrint(HeroNode head){
        if (head == null ) {
            return;
        }
        Stack<HeroNode> heroNodes = new Stack<>();
        HeroNode temp = head.next;
        while (temp != null){
            heroNodes.push(temp);
            temp = temp.next;
        }
       while (heroNodes.size()>0){
           System.out.println(heroNodes.pop());
       }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值