思路分析
- 需要首先得到单链表的长度length
- 从链表的第一个开始遍历,第length-k就是我们要寻找的节点
package com.ran;
import java.util.Scanner;
public class hello {
public static void main(String[] args) {
HeroNode hero1=new HeroNode(1,"ran","qwe");
HeroNode hero2=new HeroNode(2,"rasd","asd");
HeroNode hero3=new HeroNode(3,"zxc","zxc");
HeroNode hero4=new HeroNode(4,"asdasd","fgh");
SingleLinkedList lianbiao=new SingleLinkedList();
lianbiao.add2(hero1);
lianbiao.add2(hero4);
lianbiao.add2(hero2);
lianbiao.add2(hero3);
lianbiao.list();
System.out.println(lianbiao.changdu(lianbiao.getHead()));
System.out.println(lianbiao.daoshu(lianbiao.getHead(), 3));
}
}
//定义一个SingleLinkedList 管理我们的英雄
class SingleLinkedList {
HeroNode head = new HeroNode(0, "", "");
public HeroNode getHead() {
return head;
}
public static int changdu(HeroNode head) {
HeroNode temp = head;
int length = 0;
if (head == null) {
System.out.println("空");
System.out.println("chang du wei " + length);
}
while (true) {
if (temp.next == null) {
break;
}
length++;
temp = temp.next;
}
return length;
}
public void add2(HeroNode heroNode){
HeroNode temp=head;
boolean qwe=false;
while (true){
if (temp.next==null){
break;
}
if(temp.next.no>heroNode.no){
break;
}
else if(temp.next.no==heroNode.no){ //注意一下 都用temop.next.no判断
qwe=true;
break;
}
temp=temp.next;
}
if(qwe){
System.out.println("存在了添加不了");
}else {
heroNode.next=temp.next;
temp.next=heroNode;
}
}
public HeroNode daoshu(HeroNode head, int qq) {
if (head == null) {
System.out.println("空");
}
int size = changdu(head);
HeroNode temp=head;
while (true){
if(temp.next==null){
break;
}
if(temp.next.no==size-qq+1){
break;
}
temp=temp.next;
}
return temp.next;
}
public void list(){
if(head.next==null){
System.out.println("kong");
return;
}
HeroNode temp=head;
while (true){
if(temp.next==null){
break;
}
System.out.println(temp.next);
temp=temp.next;
}
}
}
//定义一个heroNode,每一个heroNode对象就是一个节点
class HeroNode{
public int no;
public String name;
public String chuohao;
public HeroNode next;
public HeroNode(int no, String name, String chuohao) {
this.no = no;
this.name = name;
this.chuohao = chuohao;
}
@Override
public String toString() {
return "HeroNode{" +
"no=" + no +
", name='" + name + '\'' +
", chuohao='" + chuohao + '\'' +
'}';
}
}
运行结果如下: