Article Outline
TOC
Collection Outline
1. 题目
输入一个链表,输出该链表中倒数第k个结点。
2.题解
/*
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) {
//判断链表 和 k节点是否为空
if(head == null || k == 0){
return null;
}
int count = 0;
//将链表压入栈中
Stack<ListNode> stack = new Stack<ListNode>();
while(head != null){
stack.push(head);
head = head.next;
count++;
}
//判断链表长度是否小于节点
if(count < k){
return null;
}
//将倒数第k个元素弹出
ListNode knode = null;
for(int i = 0; i < k;i++){
knode = stack.pop();
}
return knode;
}
}
3.总结
写代码要注意程序的鲁棒性,鲁棒性是指程序能够判断输入是否合乎结果,并对不合乎要求的输入予以合理的处理。