计算单链表的倒数第k个节点

    技术2022-07-10  90

    这个题的感觉很像比如要你计算100的倒数第5个数是多少? 不就是 100 - 5 = 95

    public static Hero getK(Hero head,int index){ if (head .getNext() == null){ System.out.println("链表为空!!!"); return null; } int size = getSize(head); //链表的有效节点个数 //index做校验 if (index < 0 || index > size){ System.out.println("输入的数据有误!!!"); return null; } Hero temp = head.getNext(); for (int i = 0; i < (size - index); i++) { temp = temp.getNext(); } return temp; } public static int getSize(Hero head){ if (head.getNext() == null){ System.out.println("链表为空!!!"); return 0; } Hero temp = head.getNext(); int sum = 0; while (temp != null){ sum ++; temp = temp.getNext(); } return sum; }
    Processed: 0.008, SQL: 9