剑指offer14-输入一个链表,输出该链表中倒数第k个结点

xiaoxiao2022-05-13  44

package JZoffertest; import JZoffertest.test3.ListNode; public class test14a { public ListNode FindKthToTail(ListNode head,int k) { if(head==null||k<=0) { return null; } ListNode pre=head; ListNode last=head; for(int i=1;i<k;i++) { if(pre.next!=null) pre=pre.next; else { return null; } } while(pre.next!=null) { pre=pre.next; last=last.next; } return last; } } package JZoffertest; import java.util.Stack; import JZoffertest.test3.ListNode; public class test14 { public ListNode FindKthToTail(ListNode head,int k) { 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; } }

 

转载请注明原文地址: https://www.6miu.com/read-4884214.html

最新回复(0)