题目描述
输入一个链表,输出该链表中倒数第k个结点。
解题思路:
首先,遍历链表得到链表的长度;
其次,要明白倒数第k个节点就是正数的第(length-k+1)个节点,接下来,遍历数组得到倒数第k个节点。
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
if(head == null){
return null;
}
int length = 0;
ListNode temp = head;
while(temp != null){
temp = temp.next;
length += 1;
}
if(k<1 || k >length){
return null;
}
temp = head;
for(int i = 1;i<(length-k+1);i++){
temp = temp.next;
}
return temp;
}
}