节点类
class Node{
Node next;
int data;
public Node(int data) {
this.data = data;
}
@Override
public String toString() {
return "Node [data=" + data + "]";
}
}
单链表类
class linkeList{
Node head = new Node(-1);
public void add(Node ele) {
Node temp = head;
while(temp.next != null) {
temp = temp.next;
}
temp.next = ele;
}
}
main类
public class SinglelinkedList {
public static void main(String[] args) {
linkeList ls = new linkeList();
ls.add(new Node(1));
ls.add(new Node(2));
ls.add(new Node(3));
ls.add(new Node(4));
showNode(ls,4);
}
private static void showNode(linkeList ls, int k) {
Node node = ls.head.next;
int count = 0;
while(node != null) {
node = node.next;
count++;
}
node = ls.head.next;
for(int i = count; i > k; i--) {
node = node.next;
}
System.out.println("倒数第"+ k +"个节点:"+node);
}
}
输出结果
倒数第4个节点:Node [data=1]



