码迷,mamicode.com
首页 > 其他好文 > 详细

2.2 Kth element linked list

时间:2014-11-22 10:38:33      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   sp   for   strong   on   div   

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

标签:style   blog   io   color   sp   for   strong   on   div   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!