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