【题目描述】输入一个链表,输出该链表中倒数第k个结点。
【解题思路1】
//1.设置两个指针,inx1先向后移动k-1步,inx2不动。
//2.然后同时向后移动,inx1到达结尾的时候,inx2刚好为倒数第k个结点。
//3.注意临界情况。如输入链表为空,k<=0,或者链表长度小于k等
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
if(k == 0){
return null;
}
if(head == null){
return head;
}
ListNode inx = head;
int i = 1;
while(i < k && inx.next != null){
inx = inx.next;
i++;
}
if(i<k){
return null;
}
while(inx.next !=null){
inx = inx.next;
head = head.next;
}
return head;
}
}
【解题思路2】
//1. 遍历链表,计算链表长度。
//2. 计算倒数第k个结点的正向位置和下标。
//3. 返回该结点。
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
if(head == null)
return null;
int count = 0;
ListNode temp = head;
for (int i = 0; temp != null; temp = temp.next) {
count++;
}
if(k>count)
return null;
System.out.println(count);
//一共有count个,倒数第k个就是正数第count-k+1,下标是count-k
for(int i = 0;i<count-k;i++){
head = head.next;
}
return head;
}
}