题目描述
import java.util.Stack;/*public class ListNode { int val; ListNode next = null;
ListNode(int val) { this.val = val; }}*/public class Solution { public ListNode FindKthToTail(ListNode head,int k) { /*
#以下为错误代码,为什么会错?值得思考一下
Stack<ListNode> stack=new Stack<ListNode>(); while (head!=null) { stack.push(head); head=head.next; } if(head == null || k ==0 ||k>stack.size()){ return null; } ListNode knode = null; for(int i = 0; i < k; i++){ knode = stack.pop(); } return knode; */
if(head == null || k ==0 ){ return null; } //可以先把链表反转,然后找出第k个 Stack<ListNode> stack = new Stack<ListNode>(); int count = 0; while(head != null){ stack.push(head); head = head.next; count++; } if(count < k){ return null; } ListNode knode = null; for(int i = 0; i < k; i++){ knode = stack.pop(); } return knode; }}
牛客大佬的神仙代码
代码思路如下:
两个指针,先让第一个指针和第二个指针都指向头结点,
然后再让第一个指正走(k-1)步,到达第k个节点。
然后两个指针同时往后移动,
当第一个结点到达末尾的时候,
第二个结点所在位置就是倒数第k个节点了。。
/*