快慢指针的解题思路
链表快慢指针是一种常见的算法,用于在单向链表中找到特定元素。快指针每次移动两个节点,慢指针每次移动一个节点。
1.初始化快指针和慢指针都指向链表的头节点。
2.快指针一次移动两个节点,快指针来到末尾时,慢指针就到了终点.
3.根据不同要求,初始化快慢指针时还可以做调整.
第一题:输入链表头节点,奇数长度返回中点,偶数长度返回上中点
先定义一个单链表结构:
public static class Node{
public int val;
public Node next;
public Node(int val) {
this.val = val;
}
}
代码演示快慢指针来解题:
/**
* 输入链表头节点,奇数长度返回中点,偶数长度返回上中点
* @param head
* @return
*/
public static Node midOrUpMidNode(Node head){
//为null 返回null ,只有一个节点 或者两个节点时 返回头节点
if (null == head || head.next == null || head.next.next == null){
return head;
}
//这个初始化时,就没有初始化在头节点.
Node slow = head.next;
Node fast = head.next.next;
while (fast.next != null && fast.next.next != null){
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
可以用数组来解题:也很简单.代码演示:
public static Node right(Node head) {
if (head == null) {
return null;
}
Node cur = head;
//将链表加到集合中,计算长度返回.
ArrayList<Node> arr = new ArrayList<>();
while (cur != null) {
arr.add(cur);
cur = cur.next;
}
return arr.get((arr.size() - 1) / 2);
}
第二题:输入链表头节点,奇数长度返回中点,偶数长度返回下中点
直接代码演示,一下题目都不在演示辅助集合解题的代码.熟悉下快慢指针.
/**
* 输入链表头节点,奇数长度返回中点,偶数长度返回下中点
* @param head
* @return
*/
public static Node midDownMidNode(Node head){
if (null == head || head.next == null ){
return head;
}
//这个初始化在头节点的下一个节点,是为了满足题目要求.
Node slow = head.next;
Node fast = head.next;
while (fast.next != null && fast.next.next != null){
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
第三题:输入链表头节点,奇数长度返回中点前一个,偶数长度返回上中点前一个
代码演示:
/**
* 输入链表头节点,奇数长度返回中点前一个,偶数长度返回上中点前一个
* @param head
* @return
*/
public static Node midUpUpMidNode(Node head){
if (head == null || head.next == null || head.next.next == null){
return null;
}
//初始化的节点注意
Node slow = head;
Node fast = head.next.next;
while (fast.next != null && fast.next.next != null){
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
第四题:输入链表头节点,奇数长度返回中点前一个,偶数长度返回下中点前一个
/**
* 输入链表头节点,奇数长度返回中点前一个,偶数长度返回下中点前一个
* @param head
* @return
*/
public static Node randomNode(Node head){
if (null == head || head.next == null){
return null;
}
//注意
Node slow = head;
Node fast = head.next;
while (fast.next!= null && fast.next.next != null){
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
**链表问题.要多动手,多做题,没有太好的办法.
链表问题,指针调节是比较麻烦的,也没什么好的技巧,快慢指针法也是要根据需求自己去调节的,这个这能慢慢摸索,积累,
**