输入一个链表,输出该链表中倒数第k个结点。 解析:先算出链表长度total,然后返回第total-K+1个结点。 代码: 123456789101112131415161718192021222324252627282930 public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; }}*/public class { public ListNode FindKthToTail(ListNode head,int k) { int total=0; if(head==null) return null; //这里的参数非null判断其实不加也行,若head为null则下面的代码也会返回null ListNode node=head; while(node!=null){ total++; node=node.next; } if(k<=total){ node=head; for(int i=1; i<=total-k; i++){ node=node.next; } return node; } return null; }} 赞微海报分享
近期评论