数据结构学习(二):单链表试题

一、获取单链表的节点的个数

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;
    }

二、查找单链表中倒数第K个节点

思路:

    1.编写一个方法,接收head节点,同时接收一个index
    2.index表示倒数第index个节点
    3.先把链表从头到尾遍历,得到链表的总长度(getLength)
    4.得到size后,从链表的第一个开始遍历(size-index)个,就可以得到
public static HeroNode findLastIndexNode(HeroNode head, int index) {
        if(head.next == null) {
            return null;
        }

        //第一次遍历得到链表长度
        int size = getLength(head);

        //第二次遍历size-index位置,就是我们倒数的第K个节点
        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;
    }

三、将单链表反转

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, "", "");

        while (cur != null) {
            //暂时保存当前节点的下一个节点
            next = cur.next;
            //将cur的下一个节点指向新的链表的最前端
            cur.next = reverseHead.next;
            //将cur连接到新的链表上
            reverseHead.next = cur;
            //让cur后移
            cur = next;
        }

        //将head.next指向reverseHead.next,实现单链表的反转
        head.next = reverseHead.next;

    }

四、逆序打印链表,利用栈

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());
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值