题目描述
输入一个链表,输出该链表中倒数第k个结点。
源代码:
解法一:
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
import java.util.Stack;
public class Solution {//不正确
public ListNode FindKthToTail(ListNode head,int k) {
Stack<int> s=new Stack<int>();
while(head!=null){
s.push(head.val);
head=head.next;
}
for(int i=0;i<k-1;i++)
s.pop();
return (int)s.pop();
}
}
解法二:
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {//通过了50%
public ListNode FindKthToTail(ListNode head,int k) {
if(head==null) return null;
ListNode fir=null,sec=head;
int cnt=1;
//ListNode tmp = head;
while(head!=null){
if(cnt==k){
fir=head;break;
}
head=head.next;
cnt++;
}
if(cnt<k) return null;
if(cnt==k)
fir=fir.next;
while(fir!=null){
fir=fir.next;
sec=sec.next;
}
return sec;
}
}
解法三:
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
import java.util.Stack;
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
if(head==null) return null;
Stack<ListNode> s=null;
while(head!=null){
s.push(head);
head=head.next;
}
int i=0;
while((i<=k-2)&&!s.empty()){
s.pop();
i++;
}
if(!s.empty())
return s.pop();
return null;
}
}