题目描述
输入一个链表,输出该链表中倒数第k个结点。
思路
(1)方法一:得到链表的结点个数size,让head向后走size-k步;
①若链表为空,直接返回null
②获取链表的结点个数size
③若K值不合法(k<=0||k>size),直接返回null;
④head向后走size-k步,返回此时的head即可
(2)方法二:前后指针法
①若链表为空,直接返回null
②若K值不合法(k<=0),直接返回null;
③定义两个指针front,rear
④front先走K步
⑤front,rear同步的向前走,front到达结尾时,rear即为倒数第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 size = getSize(head);
if(k<=0||k>size){
return null;
}
int step = size - k;
for(int i = 0;i<step;i++){
head = head.next;
}
return head;
}
private int getSize(ListNode head) {
int count = 0;
while(head!= null){
count++;
head = head.next;
}
return count;
}
public ListNode FindKthToTail2(ListNode head,int k) {
if(head == null){
return null;
}
if(k<=0){
return null;
}
ListNode front = head;
ListNode rear = head;
while(k>0&&front!=null){
front = front.next;
k--;
}
while(front!=null){
front = front.next;
rear = rear.next;
}
return k>0?null:rear;
}
}