![点击查看原始大小图片](http://dl.iteye.com/upload/attachment/0077/9611/3291e57e-8e26-378d-ba4c-3515fbfb9e8b.jpg)
原理:两个指针先都指向头指针的下一节点,一个指针先走K-1步,然后俩指针再一起走,后走的指针所指为所求,注意边界处理。
- class Node{
- Node link;
- int data;
- public Node(){}
- public Node(int m) {
- data = m;
- }
- }
- public class MyLinkList {
- public Node createLinkList(int[] a){
- Node head_node = new Node();
- Node temp_node = head_node;
- for(int m : a){
- Node n = new Node(m);
- temp_node.link = n;
- temp_node = n;
- }
- return head_node;
- }
- public int printK_NodeOfCountFromEnd(Node head_node,int k){
- if(null == head_node || k <= 0)
- return 0;
- Node temp1_node = head_node.link;
- for(int i = 0; i < k-1 && null != temp1_node; i++)
- temp1_node = temp1_node.link;
- if(null == temp1_node)
- return 0;
- Node temp2_node = head_node.link;
- while(null != temp1_node.link){
- temp1_node = temp1_node.link;
- temp2_node = temp2_node.link;
- }
- System.out.println(temp2_node.data);
- return 1;
- }
- public static void main(String[] args){
- MyLinkList list = new MyLinkList();
- int[] a = {1,4,2,5,3};
- list.printK_NodeOfCountFromEnd(list.createLinkList(a), 2);
- }
- }
class Node{
Node link;
int data;
public Node(){}
public Node(int m) {
data = m;
}
}
public class MyLinkList {
public Node createLinkList(int[] a){
Node head_node = new Node();
Node temp_node = head_node;
for(int m : a){
Node n = new Node(m);
temp_node.link = n;
temp_node = n;
}
return head_node;
}
public int printK_NodeOfCountFromEnd(Node head_node,int k){
if(null == head_node || k <= 0)
return 0;
Node temp1_node = head_node.link;
for(int i = 0; i < k-1 && null != temp1_node; i++)
temp1_node = temp1_node.link;
if(null == temp1_node)
return 0;
Node temp2_node = head_node.link;
while(null != temp1_node.link){
temp1_node = temp1_node.link;
temp2_node = temp2_node.link;
}
System.out.println(temp2_node.data);
return 1;
}
public static void main(String[] args){
MyLinkList list = new MyLinkList();
int[] a = {1,4,2,5,3};
list.printK_NodeOfCountFromEnd(list.createLinkList(a), 2);
}
}
运行:
C:\test>java MyLinkList
5
文章转自:[url]http://blog.csdn.net/nash_/article/details/8205491
[/url]
源码: