查找单链表中的倒数第k个节点

package algorithm.linkedlist;


/**
 * @Created by XDarker
 * @Description 查找单链表中的倒数第k个节点
 * @Date 2019/10/13 16:41
 */
public class GetLastKNode {


    public static void main(String[] args) {

        Node head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(3);
        head.next.next.next = new Node(4);
        System.out.println("========链表========");
        list(head);
        System.out.println("链表长度:" + getLength(head));
        int k = 4;
        Node KNode = findLastKNode(head, k);
        System.out.printf("链表倒数第 %d 个节点是 %d:", k, KNode.data);


    }


    //查找单链表中的倒数第k个节点
    //思路
    //1. 编写一个方法,接收head节点,同时接收一个index
    //2. k 表示是倒数第k个节点
    //3. 先把链表从头到尾遍历,得到链表的总的长度 getLength
    //4. 得到size 后,我们从链表的第一个开始遍历 (size-k)个,就可以得到
    //5. 如果找到了,则返回该节点,否则返回nulll
    public static Node findLastKNode(Node head, int k) {
        if (head == null) {
            //链表为空 没有找到
            return null;
        }
        //遍历 获取链表的长度
        int size = getLength(head);
        //遍历 获取 size - k 位置, 就是我们倒数的第 K 个节点
        if (k <= 0 || k > size) {
            return null;
        }
        Node cur = head;
        for (int i = 0; i < (size - k); i++) {
            cur = cur.next;
        }
        return cur;


    }


    /**
     * @param head 头节点
     * @return
     */
    public static int getLength(Node head) {

        if (head == null) {
            //链表为空
            return 0;
        }
        int num = 0;
        Node cur = head;
        while (cur != null) {
            num++;
            cur = cur.next;

        }
        return num;
    }

    /**
     * 显示链表
     */
    public static void list(Node head) {
        if (head == null) {
            System.out.println("链表为空");
            return;
        }
        Node temp = head;
        System.out.print("链表内容:");
        while (temp != null) {
            System.out.print(temp.data + " ");
            temp = temp.next;
        }
        System.out.println();

    }

}


class Node {
    Node next = null;//下一个结点
    int data;//结点数据

    public Node(int data) {
        this.data = data;
    }

}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值