回文链表

简单描述就是 1->2->3->2->1 这种结构,也就是正着念跟反着念是一样的。所以可以使用栈,可以使得倒过来然后再来跟正着一一比对。
java
public boolean isPalindrome(ListNode head) {
if (head == null) {
return true;
}
Stack<ListNode> listNodeHS = new Stack<>();
ListNode currentNode = head;
while (currentNode != null) {
listNodeHS.add(currentNode);
currentNode = currentNode.next;
}
// 收集完毕,将全部节点压入栈中,然后遍历原有链表
while (head != null) {
ListNode pop = listNodeHS.pop();
if (pop.val != head.val) { // 如果不匹配则直接返回false
return false;
}
head = head.next;
}
return true;
}
高级版本的操作
java
public boolean isPalindrome(ListNode head) {
if (head == null || head.next == null) return true;
ListNode slow = head; // 慢指针
ListNode fast = head; // 快指针
while (fast.next != null && fast.next.next != null) { // 快指针走得快,注意这个条件为fast.next.next/fast.next时slow分别落到那个位置
slow = slow.next;
fast = fast.next.next;
}
// 当 fast为null时则表明数量为偶数,此时慢指针走到左中心位置此时如果在往右走一步则左侧跟右侧一致(逆序)
// 当 fast不为null时则表明为奇数,此时slow刚好走到中间位置,此时它的右侧跟左侧是一样的。
// 反转链表
ListNode reverseNode = reverse(slow.next);
while (reverseNode != null) {
if (head.val != reverseNode.val) {
return false;
} else {
head = head.next;
reverseNode = reverseNode.next;
}
}
return true;
}
private ListNode reverse(ListNode head) {
if (head == null) {
return null;
}
ListNode pre = null;
ListNode next = null;
while (head != null) {
next = head.next;
head.next = pre; // 当前节点指向前一个节点
pre = head; // pre来到当前节点
head = next; // head来到下一个节点
}
return pre;
}
fast.next.next fast.next 分别落在什么位置
分隔链表
给你一个链表的头节点 head 和一个特定值 x,请你对链表进行分隔,使得所有 小于 x 的节点都出现在 大于或等于 x 的节点之前。
输入:head = 1,4,3,2,5,2, x = 3 输出:1,2,2,4,3,5
思想:就是分别整6个参数,见下图所示。然后来遍历链表,将这三种条件放到不同的位置,注意头指向尾部,最终如第二张图所示,进行串联起来,注意其中串联起来的节点有的为空的场景哦。

