找出链表倒数第K个元素
思路:可设两个头指针p1和p2,当p2开始向前走,当走的步数为k时,p1开始走,此时当p2走到结尾时,p1所指的位置正好为倒数第k个元素的位置
class ListNode{
Object val;
ListNode next;
ListNode(Object val){
this.val=val;
}
@Override
public String toString(){
StringBuilder sb=new StringBuilder();
ListNode p=next;
while(p!=null){
sb.append(p.val);
p=p.next;
}
return sb.toString();
}
}
public static class FindElem{
public static ListNode FindKthToTail(int k,ListNode head) {
ListNode p1=head;
ListNode p2=head;
int count=0;
while(p2!=null&&count<k){
p2=p2.next;
count++;
}
if(count<k)return null;
while(p2!=null){
p1=p1.next;
p2=p2.next;
}
return p1;
}
public static void main(String[]args){
ListNode head=new ListNode(null);
ListNode p=head;
int arr={1,2,3,4,5,6,7,8,9};
for(int i=0;i<arr.length;i++){
p.next=new ListNode(arr[i]);
p=p.next;
}
System.out.println(FindKthToTail(3,head).val)
}
}