原理:两个指针先都指向头指针的下一节点,一个指针先走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]
源码:
本文介绍了一种寻找链表中倒数第K个节点的方法,通过使用双指针技巧来实现高效的查找,避免了两次遍历链表的过程。




195

被折叠的 条评论
为什么被折叠?



