ListNode 的定义
package com.company;
public class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
public ListNode setNext(ListNode next) {
this.next = next;
return next;
}
@Override
public String toString() {
return "ListNode{" +
"val=" + val +
'}';
}
}
左右指针法
package com.company;
public class KthFromTail_Offer22 {
public static ListNode kthNodeFromEnd(ListNode head, int k){
if( k <= 0 || head == null){
return null;
}
ListNode pRight = head, pLeft = null;
/* pRight moves k-1 steps from the start */
for(int i=1; i<k; i++){
if(pRight != null){
pRight = pRight.next;
}
}
while(pRight != null){
if(pLeft == null){
pLeft = head;
}else{
pLeft = pLeft.next;
}
pRight = pRight.next;
}
if(pLeft != null){
return pLeft;
}
return null;
}
public static void main(String[] args){
ListNode head = new ListNode(1);
head.setNext(new ListNode(2))
.setNext(new ListNode(3))
.setNext(new ListNode(4))
.setNext(new ListNode(5))
.setNext(new ListNode(6));
System.out.println(kthNodeFromEnd(head, 3));
System.out.println(kthNodeFromEnd(head, 0));
System.out.println(kthNodeFromEnd(head, 8));
}
}