题目描述:
输入一个链表,输出该链表中倒数第k个结点
思路:先得出链表长度count,再遍历(count-k),就得到了倒数第k个节点的数。
代码:
package offer;
public class TestNo14 {
static class ListNode{
int val;
ListNode next;
ListNode(int x){
val = x;
}
}
public static void main(String[] args) {
ListNode head = new ListNode(0);
ListNode newNode = head;
for(int i = 0;i<7;i++){
newNode.next = new ListNode(i);
newNode = newNode.next;
}
System.out.println(new TestNo14().FindKthToTail(head,3).val);
}
public ListNode FindKthToTail(ListNode head,int k) {
if(head == null || k <=0){
return null;
}
ListNode node = head;
int count = 0;
while (node!= null){
node = node.next;
count++;
}
if(count<k){
return null;
}
ListNode node1 = head;
for(int i = 0;i<count-k;i++){
node1 = node1.next;
}
return node1;
}
}