本文总结了常见高频的关于链表的算法考察。
1.如何找到链表的中间元素?
我们可以采用快慢指针的思想,使用步长为1的慢指针和步长为2的快指针,当快指针抵达链表末尾时,此时慢指针指向的即为中点位置。
public static LinkNode findMiddleByPointer(LinkNode node) {
LinkNode slow = node;
LinkNode fast = node;
// 检测快指针是否可以安全移动
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
我们还可以采用递归的方式,当递归到最末尾的时候,我们已经能知道链表的长度,此时当递归回去的时候,判断当前递归层级等于链表长度一半的时候,即为链表的重点。
public static void findMiddleByRecursion(LinkNode node, int recursionIndex) {
if (node.next != null) {
findMiddleByRecursion(node.next, recursionIndex + 1);
} else {
middleIndex = recursionIndex % 2 == 0 ? recursionIndex / 2 : recursionIndex / 2 + 1;
}
if (middleIndex == recursionIndex) {
System.out.println(node.value);
}
return;
}
2.检测链表是否有环。
检测链表是否有环是非常常见的算法考察。常见的就是使用快慢指针,如果快慢指针有重合的时候,说明链表是有环的。
public static boolean isExistCircle(LinkNode node) {
LinkNode slow = node;
LinkNode fast = node;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
return true;
}
}
return false;
}
3.如何列表反转(递归)
我们可以在递归回溯的时候,反向更改节点的指针。
public stati