package demo;
/*
public class headNode {
int val;
headNode next = null;
headNode(int val) {
this.val = val;
}
}*/
/*
* 题目描述
输入一个链表,输出该链表中倒数第k个结点。
*/
public class Solution {
public headNode FindKthToTail(headNode head,int k) {
if(head == null)
return head;
headNode node = head;
int count = 0;//record number of nodes
while(node != null) {
count++;
node = node.next;
}
if(count < k)
return null;//can not find node of k
headNode h = head;
for(int i=0;i<count-k;i++) {
h = h.next;
}
return h;
}
public static void main(String[] args) {
headNode head=new headNode(1);
headNode head1=new headNode(2);
headNode head2=new headNode(3);
headNode head3=new headNode(4);
headNode head4=new headNode(5);
head.next = head1;
head1.next = head2;
head2.next = head3;
head3.next = head4;
head4.next = null;
Solution s = new Solution();
System.out.println(s.FindKthToTail(head, 3).val);
}
}
class headNode {
int val;
headNode next = null;
headNode(int val) {
this.val = val;
}
}
输出该链表中倒数第k个结点
最新推荐文章于 2021-03-12 15:08:29 发布