双指针之快慢指针
1、判定链表中是否含有环
2、已知链表中含有环,返回这个环的起始位置
3、寻找链表的中点
4、寻找链表的倒数第 k 个元素
public class LinkedListPointer {
public static boolean hasCycle(ListNode head) {
if (head == null || head.next == null) {
return false;
}
ListNode slow = head;
ListNode fast = head.next;
while (slow != null && fast != null) {
if (slow == fast) {
return true;
}
slow = slow.next;
fast = fast.next.next;
}
return false;
}
public static ListNode cycleHead(ListNode head) {
if (head == null || head.next == null) {
return null;
}
ListNode slow = head;
ListNode fast = head.next;
while (slow != null && fast != null) {
if (slow == fast) {
return slow;
}
slow = slow.next;
fast = fast.next.next;
}
return null;
}
public static ListNode middle_node(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode slow = head;
ListNode fast = head.next;
while (slow != null && fast != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
public static ListNode ds_k_node(ListNode head, int k) {
if (head == null) {
return null;
}
ListNode slow = head;
ListNode fast = head;
for (int i = k; i > 0; i --) {
fast = fast.next;
if (fast == null) {
return null;
}
}
while (slow.next != null && fast.next != null) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
public static void main(String[] args) {
ListNode head = ListNode.createOne();
ListNode.printN(head);
System.out.println(hasCycle(head));
System.out.println(middle_node(head).val);
System.out.println( ds_k_node(head, 1).val);
System.out.println( ds_k_node(head, 0).val);
System.out.println( ds_k_node(head, 10));
System.out.println( ds_k_node(head, 4).val);
}
}