几道单链表面试题

36 阅读1分钟

4.3单链表的几道面试题

1.求单链表有效节点的个数(不统计头结点)

/**
     *
     * @param head 传入单链表的头结点
     * @return 返回链表长度
     */
    public static int getLinkedListLength(HeroNode head) {
        if(head.next == null) {
            return 0;
        }
        HeroNode temp = head.next;
        int length = 0;
        while (temp != null) {
            length ++;
            temp = temp.next;
        }
        return length;
    }

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

思路:

1 编写一个方法,接受待查找的单链表的头结点和K,K表示倒数第K个节点 2 遍历链表,获得链表的长度size 3 得到size后,遍历链表size-k次,就可以得到查找的节点

/**
     * 思路: 1 编写一个方法,接受待查找的单链表的头结点和K,K表示倒数第K个节点
     * 2 遍历链表,获得链表的长度size
     * 3 得到size后,遍历链表size-k次,就可以得到查找的节点
     * @param head 传入待查找的单链表的头结点
     * @param k 传入倒数第K个的K
     * @return 传回倒数第K个节点,没找到返回空
     */
    public static HeroNode getLastHero(HeroNode head, int k) {
        if(head.next == null) {
            return null;
        }
        int num = getLinkedListLength(head) - k;
        if (num < 0 || num > getLinkedListLength(head)) {
            return null;
        }else{
            HeroNode cur = head.next;
            for(int i=0; i<num; i++ ){
                cur = cur.next;
            }
            return cur;
        }
    }

3.单链表的反转

思路:

1659853655068.png

    /**
     * 
     * @param head 传入待反转的单链表
     */
    public static void reverseLinkedList(HeroNode head) {
        if(head.next == null || head.next.next == null) {
            return;
        }
        HeroNode newHeadNode = new HeroNode(0, "", "");
        HeroNode cur = head.next; // 辅助指针变量,帮助我们遍历原链表
        HeroNode temp; // 保存当前节点的下一个节点,防止丢失
        while (cur != null) {
            temp = cur.next; // 先暂存下一个节点
            cur.next = newHeadNode.next; // 当前节点的下一个节点指向新链表头结点的下一个位置
            newHeadNode.next = cur; // 头结点指向当前节点
            cur = temp; // 当前节点往后移
        }
        head.next = newHeadNode.next;
        return;
    }

4.从尾到头打印单链表

两个思路:

  1. 反转单链表,再打印(不推荐,会改变原链表)
  2. 将链表压入栈,并打印
public static void reversePrintLinkedList(HeroNode head) {
        if(head.next == null) {
            return;
        }
        Stack<HeroNode> stack = new Stack<HeroNode>();
        HeroNode cur = head.next;
        while (cur != null) {
            stack.push(cur);
            cur = cur.next;
        }
        while (stack.size() > 0) {
            System.out.println(stack.pop());
        }
    }

\