题目描述
输入一个链表,输出该链表中倒数第k个结点。
思路一:
设置两个指针pre和last,先让pre移动k-1步,如果此时pre为空,则k>链表长度,返回null,否则让pre和last同时移动。步骤为:
①pre=pre.next;
②if(pre==null),若为真,进入④,否则进入③;
③last=last.next,进入①;
④return last.
代码:
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
ListNode pre = head;
ListNode last = head;
if(head==null||k<1)
return null;
for(int i=0;i<k-1;i++){
pre = pre.next;
if(pre==null)
return null;
}
pre = pre.next;
while(pre!=null)
last = last.next;
pre = pre.next;
}
return last;
}
}
思路二:
先遍历一次链表得到长度n,则第n-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) {
ListNode index = head;
int length=0;
if(head==null||k<1)
return null;
while(index!=null){
length++;
index = index.next;
}
if(k>length)
return null;
for(int i=0;i<length - k;i++){
head = head.next;
}
return head;
}
}