首页 > 其他 > 详细

2.2 Kth element linked list

时间:2014-11-22 10:35:19      阅读:157      评论:0      收藏:0      [点我收藏+]

Problem

Implement an algorithm to find the kth to last element of a singly linked list.

Solution

 1 public static ListNode findElement(ListNode head, int k) {
 2     if(k <= 0)    return null;
 3     
 4     ListNode fast = head;
 5     ListNode slow = head;
 6     
 7     for(int i=0; i<k-1; i++) {
 8         if(fast == null) return null; //edge case
 9         fast = fast.next;
10     }
11     
12     //fast = null
13     if(fast == null) {
14         return null;
15     }
16     
17     while(fast.next != null) {
18         fast = fast.next;
19         slow = slow.next;
20     }
21     
22     return slow;
23 }

 

2.2 Kth element linked list

原文:http://www.cnblogs.com/superbo/p/4114793.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!