Seeking a single list penultimate K values
topic:
Single list to find the inverse element of K, such as to order the list: the penultimate element 2 1-> 2-> 3-> 4-> 5, the chain 4 is
- Construct a simple singly linked list
Thinking
Code
1, each node comprising a single linked list pointer that points to a node data and
public class LNode {
int data; //数据域
LNode next; //下一个节点的引用
}
2, the sequence is traversed twice, the first time through the entire length of n is obtained the list, the second pass of the obtained n-k + 1 th element is the reciprocal of K elements, this method requires to traverse the list twice
3, the speed of the pointer method is to use two pointers, a pointer quickly, a slow pointer, the head pointer to the first two nodes, and then quickly move the pointer K positions, this time the distance between two pointers is K, then two Meanwhile pointer movement, when the node is null pointer quickly when the pointer is the node slow penultimate node K
public class _015 {
/**
* 快慢指针法
* @param head 链表的头节点
* @param k
* @return
*/
public static LNode FindLastK(LNode head, int k) {
if (head == null || head.next == null)
return head;
LNode slow, fast;
slow = fast = head.next;
int i;
for (i = 0; i < k && fast != null; ++i) {
fast = fast.next;
}
if (i < k)
return null;
while (fast != null) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
//顺序遍历两遍法
public static LNode findLastK1(LNode head, int k) {
if (head == null || head.next == null)
return head;
LNode tmpLNode = head.next;
int n = 0;
while (head.next != null) {
n++;
head = head.next;
}
head.next = tmpLNode;
int t = n - k + 1;
while (head.next != null) {
if (t == 0)
return head;
t--;
head = head.next;
}
return null;
}
/**
* 构造一个带有头节点的链表
* head->1->2->3->4->5
* @param args
*/
public static void main(String[] args) {
LNode head = new LNode();
head.next = null;
LNode tmp = null;
LNode cur = head;
for (int i = 1; i < 7; i++) {
tmp = new LNode();
tmp.data = i;
tmp.next = null;
cur.next = tmp;
cur = tmp;
}
for (cur = head.next; cur != null; cur = cur.next) {
System.out.print("构造的链表:"+cur.data + " ");
}
System.out.println();
System.out.println("快慢指针求得的数值:"+FindLastK(head, 3).data);
System.out.println("顺序遍历两遍求得的值:"+findLastK1(head, 3).data);
}
}