满足下面两个要求:
(1)正序构建链表;
(2)构建后要忘记链表长度。
import java.util.Scanner;
/**
* 【输出单向链表中倒数第k个结点】
*
*
*/
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int size = sc.nextInt();
ListNode listNode = new ListNode();
for (int i = 0; i < size; i++) {
int value = sc.nextInt();
listNode.add(value);
}
int index = sc.nextInt();
System.out.println(listNode.get(index));
}
}
}
class ListNode {
// 首节点
Node first;
// 尾节点
Node last;
/**
* 新增节点
* @param value
*/
public void add(Integer value) {
Node node = new Node(value, null, null);
if (first == null) {
first = node;
last = node;
return;
}
Node headNode = first;
while (headNode.getNext() != null) {
headNode = headNode.getNext();
}
headNode.setNext(node);
node.setHead(headNode);
last = node;
}
/**
* 根据位置获取节点
* @param index
* @return
*/
public Integer get(Integer index) {
Node lastNode = last;
for (int i = 0; i < index - 1; i++) {
lastNode = lastNode.getHead();
}
return lastNode.value;
}
private class Node{
int value;
// 前节点
Node head;
// 后节点
Node next;
public Node(int value, Node head, Node next) {
this.value = value;
this.head = head;
this.next = next;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public Node getHead() {
return head;
}
public void setHead(Node head) {
this.head = head;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
}