算法列表
判定链表中是否含有环 已知链表中含有环,返回这个环的起始位置 寻找无环单链表的中点 寻找单链表的倒数第k个元素(k不超过链表的长度)
代码
package com. company;
import static java. lang. System. out;
import java. util. *;
public class Main {
public class ListNode {
int val;
ListNode next;
ListNode ( int val) {
this . val = val;
this . next = null;
}
}
boolean hasCycle ( ListNode head) {
ListNode fast, slow;
fast = slow = head;
while ( fast != null && fast. next != null) {
fast = fast. next. next;
slow = slow. next;
if ( fast == slow)
return true ;
}
return false ;
}
ListNode detectCycle ( ListNode head) {
ListNode fast, slow;
fast = slow = head;
while ( fast != null && fast. next != null) {
fast = fast. next. next;
slow = slow. next;
if ( fast == slow) break ;
}
slow = head;
while ( slow != fast) {
slow = slow. next;
fast = fast. next;
}
return slow;
}
ListNode getMiddlePosition ( ListNode head) {
ListNode fast, slow;
fast = slow = head;
while ( fast != null && fast. next != null) {
fast = fast. next. next;
slow = slow. next;
}
return slow;
}
ListNode getLastOfK ( ListNode head, int k) {
ListNode fast, slow;
fast = slow = head;
for ( int i = 0 ; i < k; i++ ) {
fast = fast. next;
}
while ( fast != null) {
fast = fast. next;
slow = slow. next;
}
return slow;
}
public static void main ( String[ ] args) {
}
}
如果你认为对你有用,关注我的微信公众号支持我一下吧!~