前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >单链表常见面试题

单链表常见面试题

作者头像
桑鱼
发布2020-03-17 18:27:17
3670
发布2020-03-17 18:27:17
举报

统计单链表中有效节点的个数

代码语言:javascript
复制
public class Test{
    /**
     * 获取单链表的有效节点的个数,不包括头节点
     * @param head 链表的头节点
     * @return 返回的是有效节点的个数
     */
    public static int getLength(HeroNode head){
        if(head.next == null){ // 空链表
            return 0;
        }
        int length = 0; //定义一个辅助的变量,从head.next开始统计,不统计头节点
        HeroNode cur = head.next;
        while (cur != null){
            length++;
            cur = cur.next;
        }
        return  length;
    }
}

查找单链表中的倒数第k个节点(Sina)

代码语言:javascript
复制
public class Test{
    /**
     * 查找单链表中的倒数第k个节点
     * 1. 通过遍历,得到链表的总长度
     * 2. 得到长度后,链表的第size - index个,就是倒数第index个节点
     * 3. 通过遍历获得size - index 节点,如果有返回节点,否则返回null
     * @param head 头节点
     * @param index 倒数第index个节点
     * @return
     */
    public static HeroNode findLastIndexNode(HeroNode head,int index){
        if(head.next == null){
            return null; // 判断链表是否空,是返回null
        }
        int size = getLength(head);
        if(index <= 0 || index > size){
            return null; // 判断index是否小于0 或者 大于节点的个数,小于0或大于size返回null
        }
        HeroNode cur = head.next; // 定义辅助变量,通过辅助变量遍历链表,得到size - index,即倒数index
        for(int i = 0; i < size - index;i++){
            cur = cur.next;
        }
        return cur;
    }
}

单链表的反转(Tencent)

第一次移动

第二次移动

第三次移动

代码语言:javascript
复制
public class Test{
    /**
     *  将单链表反转
     * @param head
     */
    public static void reverseList(HeroNode head){
        if(head.next == null || head.next.next == null){ // 链表为空,或只有1个节点,直接返回
            return;
        }

        HeroNode cur = head.next; // 定义一个变量,用来遍历
        HeroNode next = null; // 保存当前节点的下一个节点
        HeroNode reverseHead = new HeroNode(0,"",""); // 创建一个新的链表

        while (cur != null){
            next = cur.next; // 暂时保存当前节点的下一个节点
            cur.next = reverseHead.next; // 将当前节点的下一个节点链接到新链表中最前面的节点
            reverseHead.next = cur; // 将当前节点链接到新链表
            cur = next; // cur后移
        }
        head.next = reverseHead.next; // 将head.next指向reverseHead.next,实现反转
    }
}

从尾到头打印单链表(Baidu)

代码语言:javascript
复制
public class Test{
    /**
     * 利用栈先进后出的特点,实现逆序打印的效果
     * @param head
     */
    public static void reversePrint(HeroNode head){
        if(head.next == null){
            return;
        }
        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()); // 出栈并打印
        }
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档