剑指offerNo14. 链表中倒数第k个结点(Java)

题目描述:

输入一个链表,输出该链表中倒数第k个结点

思路:先得出链表长度count,再遍历(count-k),就得到了倒数第k个节点的数。

代码:

package offer;

public class TestNo14 {
    static class ListNode{
        int val;
        ListNode next;
        ListNode(int x){
            val = x;
        }
    }
    public static void main(String[] args) {
        ListNode head = new ListNode(0);
        ListNode newNode = head;
        for(int i = 0;i<7;i++){
            newNode.next = new ListNode(i);
            newNode = newNode.next;
        }
        System.out.println(new TestNo14().FindKthToTail(head,3).val);

    }
    public ListNode FindKthToTail(ListNode head,int k) {
        if(head == null || k <=0){
            return null;
        }
        ListNode node = head;
        int count = 0;
        while (node!= null){
            node = node.next;
            count++;
        }
        if(count<k){
            return null;
        }
        ListNode node1 = head;
        for(int i = 0;i<count-k;i++){
            node1 = node1.next;
        }
        return node1;
    }

}
发布了53 篇原创文章 · 获赞 11 · 访问量 3822

猜你喜欢

转载自blog.csdn.net/qq_40664693/article/details/104359683