《剑指offer—面试题22:链表中倒数第k个节点》

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011296723/article/details/81706243

《剑指offer—面试题22:链表中倒数第k个节点》
注明:仅个人学习笔记

/**
*
* 求链表倒数第k个元素
* 本题在代码实现难度不高的情况下,主要考察输入的合法性检查是否考虑的周全
* SingleLinkedList:单链表操作
* Node:链表节点
* 这两个实现类详见《剑指offer—面试题18:删除链表的节点》 https://blog.csdn.net/u011296723/article/details/81670532
*
*/
public class ListDaoShuNoK
{
public static Node findListDaoShuNoK(Node head, int k)
{
// 头节点为空时,链表中无元素||k=0时,不存在倒数第0个节点
if (head == null || k == 0)
{
System.out.println(“该链表中无元素”);
return null;
}

    // 统计链表长度
    int length = 0;
    Node tmp = head;
    while (tmp != null)
    {
        length++;
        tmp = tmp.next;
    }
    // 当链表长度不足k个时,无法完成查找
    if (length < k)
    {
        System.out.println("链表元素不足" + k + "个,请输入元素个数大于" + k + "的链表");
        return null;
    }
    // 当链表长度恰为k个时,即链表头节点即为所求。这一步检查可以不需要。
    if (k == length)
    {
        System.out.println("倒数第" + k + "个元素,即为链表首节点");
        return head;
    }

    Node p1 = head;
    Node p2 = head;

    // p1先走k-1个节点
    int count = 0;
    while (count != k - 1)
    {
        count++;
        p1 = p1.next;
    }

    while (p1.next != null)
    {
        p1 = p1.next;
        p2 = p2.next;
    }

    return p2;
}

public static void main(String[] args)
{
    SingleLinkedList list = new SingleLinkedList();

    list.addNode(1);
    list.addNode(2);
    list.addNode(3);
    list.addNode(4);
    list.addNode(5);
    list.addNode(6);

    try
    {
        // Node k = findListDaoShuNoK(list.head, 0);
        // Node k = findListDaoShuNoK(list.head, 9);
        Node k = findListDaoShuNoK(list.head, 6);

        int data = k.data;
        System.out.println(data);
    } catch (Exception e)
    {
        System.out.println();
        System.out.println("输入不合法,请检查,并根据提示完成修改");
        // e.printStackTrace();
    } finally
    {
        System.out.println();
        System.out.println("程序执行完毕!");
    }

}

}

猜你喜欢

转载自blog.csdn.net/u011296723/article/details/81706243