单链表一些面试题

题1

//返回有效节点个数
    public static int getLength(HeroNode head){
        if (head.next==null){
            return 0;
        }
        int length=0;
        //定义一个辅助的变量,这里不统计头结点
        HeroNode cur=head.next;
        while (cur!=null){
            length++;
            cur=cur.next;
        }
        return length;
    }

题2

//查找单链表中的倒数第k个节点

    /**
     *思路
     * 1.编写一个方法,接受head节点,同时接收一个index
     * 2.index表示是倒数第index个节点
     * 3.先把链表从头到尾遍历,得到总长度getLength
     * 4.得到size后,我们从链表的第一个开始遍历(size-index)个,就可以得到
     * 5.如果找到就返回该节点,否则返回空
     */

    public  static HeroNode findLastIndexNode(HeroNode head,int index){
        if(head.next==null){
            return null;
        }
        int size=getLength(head);
        if(index<=0||index>size){
            return null;
        }
        //定义一个辅助变量,for循环定位到倒数的index
        HeroNode cur=head.next;
        for (int i = 0; i <size-index ; i++) {
            cur=cur.next;
        }
        return cur;
    }

题3

//将单链表反转
    public static void reverseList(HeroNode head){
        //如果当前链表为空,或者只有一个节点不用反转'
        if(head.next==null||head.next.next==null){
            return;
        }
        HeroNode cur=head.next;
        HeroNode next=null;
        HeroNode reverseHead=new HeroNode(0,"","");
        //遍历原来的链表,将其放到新的链表reverseHead头部
        while (cur!=null){
            next=cur.next;
            cur.next=reverseHead.next;
            reverseHead.next=cur;
            cur=next;
        }
        head.next=reverseHead.next;
    }

题4

//从尾到头打印单链表 【百度,要求方式 1:反向遍历 。 方式 2:Stack 栈】
    //采用方式2
    public static void reverse(HeroNode head){
        if(head.next==null){
            System.out.println("链表空");
        }
        Stack<HeroNode> stack = new Stack<>();
        HeroNode cur=head.next;
        while (cur!=null){
            stack.push(cur);
            cur=cur.next;
        }
        while (stack.size()>0){
            System.out.println(stack.pop());
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值