查找单链表倒数第K个结点?
方法如下:
public static HeroNode findLastIndexNode(HeroNode head,int lastindex){
if(head.next==null){
return null;
}
int size = getListLength(head);
HeroNode cur=head.next;
if (lastindex<=0||lastindex>size){
return null;
}
for (int i=0;i<size-lastindex;i++){
cur=cur.next;
}
return cur;
}
然后这里我补充一下其他代码:
public static int getListLength(HeroNode head){
if(head.next==null){
return 0;
}
int length=0;
HeroNode cur=head.next;
while (cur!=null){
length++;
cur=cur.next;
}
return length;
}
class SingleLinkedList1 {
private HeroNode head = new HeroNode(0, "", "");
public HeroNode getHead() {
return head;
}
//加入到链表的最后位置
public void add(HeroNode heroNode) {
HeroNode temp = head;
while (true) {
if (temp.next == null) {
break;
}
temp = temp.next;
}
temp.next = heroNode;
}
//通过指定位置加入
public void addByOrder(HeroNode heroNode){
HeroNode temp=head;
boolean flag = false;
while (true){
if(temp.next==null){
break;//链表已经结束循环遍历
}else if (temp.next.no>heroNode.no){
break;
}else if (temp.next.no==heroNode.no){
flag=true;
break;
}
temp=temp.next;
}
if (flag==true){
System.out.printf("您的编号%d已经添加过了",heroNode.no);
}
heroNode.next=temp.next;
temp.next=heroNode;
}
public void delete(int no){
HeroNode temp =head;
boolean flag=false;
while (true){
if (temp.next==null){
break;
}else if (temp.next.no==no){
flag =true;
break;
}
temp=temp.next;
}
if (flag){
temp.next=temp.next.next;
}else {
System.out.println("不存在该编号,无法删除~");
}
}
public void list() {
if (head.next == null) {
System.out.println("链表为空");
return;
}
HeroNode temp = head.next;
while (true) {
if (temp == null) {
break;
}
System.out.println(temp);
temp = temp.next;
}
}
}
class HeroNode {
public int no;
public String name;
public String nickname;
public HeroNode next;
public HeroNode(int no, String name, String nickname) {
this.no = no;
this.name = name;
this.nickname = nickname;
}
@Override
public String toString() {
return "heroNode{" +
"no=" + no +
", name='" + name + '\'' +
", nickname='" + nickname + '\'' + "}";
}
}
欢迎大家在评论区讨论~