首页 > 其他 > 详细

链表中倒数第k个节点

时间:2019-03-03 15:37:58      阅读:114      评论:0      收藏:0      [点我收藏+]

题目:

输入一个链表,输出该链表倒数第k个节点。

 

 

解答:

 1 public class Solution {
 2 
 3     public static ListNode findKthToTail(ListNode pHead, int k) {
 4         if(pHead == null || k == 0) {
 5             return null;
 6         }
 7 
 8         ListNode pAhead = pHead;
 9         ListNode pBehind = null;
10         for(int i = 0; i < k; i++) {
11             if(pAhead.next != null) {
12                 pAhead = pAhead.next;
13             } else {
14                 return null;
15             }
16         }
17 
18         pBehind = pHead;
19         while(pAhead.next != null) {
20             pAhead = pAhead.next;
21             pBehind = pHead.next;
22         }
23 
24         return pBehind;
25     }
26 }

技术分享图片

 

链表中倒数第k个节点

原文:https://www.cnblogs.com/wylwyl/p/10465779.html

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