高质量代码-链表中倒数第k个结点

题目描述:

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

思路:

首先检查参数的合法性,head==null或节点数小于k都直接返回null。

让head先前进k-1步,ans指向头结点,然后head前进一步,ans也前进一步。当head到达最后一个节点时,ans指向倒数k个节点。时间复杂度O(n)。

解决:

 1 /*
 2 public class ListNode {
 3     int val;
 4     ListNode next = null;
 5 
 6     ListNode(int val) {
 7         this.val = val;
 8     }
 9 }*/
10 public class Solution {
11     public ListNode FindKthToTail(ListNode head,int k) {
12        
13         ListNode ans =  head;
14         
15         if (head == null || k < 1) {
16             return null;
17         }
18         int i = k;
19         //head先前进k-1个节点
20         while (i > 1 && head.next != null) {
21             head = head.next;
22             i--;
23         }
24         //节点总数不够
25         if (i != 1) {
26             return null;
27         }
28         
29         while (head.next != null) {
30             head = head.next;
31             ans = ans.next;
32         }
33        
34         return ans;
35         
36     }
37 }
原文地址:https://www.cnblogs.com/gatsbydhn/p/5346367.html