public class Link{
private LinkNode headLink= new LinkNode("");
public void add(String object){
LinkNode link1 = new LinkNode("link1");
LinkNode newNode = new LinkNode(object);
newNode.link = null;
if(headLink.link==null){
headLink.link = newNode;
}
else{
link1.link = headLink.link;
while(link1.link.link!=null){
link1.link = link1.link.link;
}
link1.link.link = newNode;
}
}
public String getKNodeBeforeLast(int k){
LinkNode linkk = new LinkNode("linkk");
LinkNode linkk2 = new LinkNode("linkk");
linkk.link = headLink.link;//指在第一个节点位置
linkk2.link = headLink.link;//指在第一个节点位置
int i = 1;//记录先行“指针”的位置
while(linkk2.link.link!=null) {
linkk2.link = linkk2.link.link;
i++;
if(i>k){//需要注意的地方
linkk.link = linkk.link.link;
}
}
if(i>=k){
System.out.println("倒数第"+k+"元素的值是:"+linkk.link.data);
return "1";
}
else{
System.out.println("少于"+k+"个元素");
return "0";
}
}
}
class LinkNode{
LinkNode link;
String data;
LinkNode(String data){
this.data = data;
link = null;
}
}
public class LinkTest {
public static void main(String[] args) {
Link link = new Link();
for (int i = 1; i <= 12; i++) {
link.add("string"+String.valueOf(i));
}
System.out.println(link.getKNodeBeforeLast(1));
}
}