## 链表中求倒数第几个元素并打印出来

``````package com.qey.learn;

import com.sun.org.apache.xerces.internal.dom.PSVIAttrNSImpl;
import jdk.nashorn.internal.ir.LiteralNode;

/**
* @ClassName Listed
* @Description
* @Author qianxl
* @Date 2021-03-11 17:12
* @Version 1.1
**/

/**
* 链表分为包含头节点
* 不包含头节点  两种类型
*/
public class Listed {

private int data;
private Listed next;

public Listed(int data) {
this.data = data;
}

public Listed getNext() {
return next;
}

public void setNext(Listed next) {
this.next = next;
}

public void showListed() {
Listed temp = this.next;
if (this == null) {
System.out.println("数据为空");
}
while (temp != null) {
System.out.println(temp.data);
temp = temp.next;
}
}

Listed p = this;
if (p.next == null) {
p.next = listed;
return this;
}
Listed temp = p.next;
while (p != null) {
temp = p;
p = p.next;
}
temp.setNext(listed);
return this;

}

/**
* 逻辑思路分析：
* （1）找到倒数下标p1 比如  倒数2  p1为1 则p2 为2  ;循环 p1=p1.next
*      则当p2=p2.next  当p2.next==null为最后一个元素时，则p1就是倒数第二元素
*      Lastposition =1 时则p1 倒数第二个元素  lastPosition -=1;
* @param lastPosition 倒数位置
* @return
*/
public Listed findLastN(  int lastPosition) {
if(lastPosition<=0){
System.out.println("下标从1开始");
return null;
}
lastPosition -=1;
Listed temp = this.next;
Listed p1 = this.next;
//临界条件
if (p1 == null) {
return null;
}

Listed p2 = p1;
while (p2 != null&& lastPosition>0) {
lastPosition--;
p2 = p2.next;
}

// 第一种情况就两个节点
if (p2.next == null) {
this.next = this.next.next;
}
//第二种情况 多个节点
while (p2 != null) {

if ( p2.next == null) {

temp.next = temp.next.next;//;
return this;
} else {
temp = p1;
p1 = p1.next;
p2 = p2.next;
}

}
return this;
}

}

public static void main(String[] args) {

lastN.showListed();

}
}
``````