链表中倒数第k个结点

链表中倒数第k个结点

http://www.nowcoder.com/questionTerminal/529d3ae5a407492994ad2a246518148a

/*
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 || k<=0)
            return null;
        Stack<ListNode> stack=new Stack<>();
        while (head!=null){
            stack.push(head);
            head=head.next;
        }
        if (stack.size()<k){
            return null;
        }
        int i=1;
        ListNode listNode=null;
        while (i<=k && !stack.isEmpty()){
            listNode=stack.pop();
            i++;
        }
        return listNode;
    }
}

全部评论

相关推荐

10-09 16:23
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务