数据结构之带头结点单链表面试题public int getLength(Node head){ if (head.next == null){ return 0

一、得到链表中的有效节点个数,不包括头节点。

这个题较简单,不啰嗦直接上代码:

public int getLength(Node head){
        if (head.next == null){
            return 0;
        }
        //链表中的第一个节点
        Node cur = head.next;
        int count = 0;
        while (cur != null){
            count++;
            cur = cur.next;
        }
        return count;
    }

二、查找倒数第index的节点,找到返回该节点,没有找到返回null。

查找之前,先判断给的index值是否合理(即不能小于0,也不能大于链表的有效节点个数)。从链表的第一个节点开始遍历有效节点个数-index次,当前节点所在位置即为倒数第index的节点。结合代码看看吧:

/**
     * 查找倒数第index的节点,找到返回该节点,没有找到返回null
     * @param index
     * @return
     */
    public Node findAsIndexNode(int index,Node head){
        if (head.next == null){
            return null;
        }
        Node cur = head.next;
        //判断index是否合理
        if (index < 0 || index > getLength(head)){
            throw new RuntimeException("所给下标不合理,请重新给值!");
        }
        //从第一个节点遍历总个数-index次,该位置的节点就是要找的节点
        for (int i = 0; i < getLength(head)-index; i++) {
            cur = cur.next;
        }
        return cur;
    }

三、单链表翻转

翻转之前先判断链表中的节点个数,若没有节点或只有一个节点则不要翻转,否则需要翻转。翻转时,创建一个新的头节点,遍历原有链表,遍历一个就把一个节点头插到新头节点所指的链表中,知道原有链表遍历完,在将原有链表的头指针指向新的头指针即可。结合代码看看吧。

public void reverseLinked(Node head){
        //链表为空或者只有一个元素时不用翻转
        if (head.next == null || head.next.next == null){
            return;
        }
        Node cur = head.next;//链表的第一个元素
        //cur的下一个元素,因为在翻转的过程中会断开cur与后面元素的连接,
        // 所以需要保存下cur的下一个元素。
        Node next = null;
        Node reverseHead = new Node(0,"");
        while (cur != null){
            next = cur.next;
            cur.next = reverseHead.next;
            reverseHead.next = cur;
            cur = next;
        }
        this.head = reverseHead;
    }

四、逆向打印链表中的节点。

逆向打印链表的方式有两种:

①根据三将链表翻转,依次遍历打印(此种方式不推荐,因为翻转链表改变了原有链表的结构)②遍历链表时将每个节点压入栈中,在依次出栈打印(推荐,借助栈的先进后出完成逆向打印)

public void reversePrint(Node head){
        if (head.next == null){
            System.out.println("链表为空,无法打印");
            return;
        }
        Stack<Node> stack = new Stack<>();
        Node 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、付费专栏及课程。

余额充值