链表中倒数第k个结点

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

解析:先算出链表长度total,然后返回第total-K+1个结点。
  
代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

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;
}
}