什么是回文结构?
回文结构就是正着读和倒着读都一样!!!
链表题的策略就是一个有容器的解法和没容器的解法.
首先我们要抓住中点就是--->分别从头遍历和从尾遍历,看看分别是否相等
有容器:
public static boolean isPalindrome1(Node head){
if(head==null || head.next==null){
return true;
}
Node cur = head;
Stack<Node> stack = new Stack<>();
while(cur!=null){
stack.push(cur);
cur = cur.next;
}
while(!stack.isEmpty()){
if(stack.pop().val!=head.val){
return false;
}else{
head = head.next;
}
}
return true;
}
首先栈的结构正好能够满足倒叙的要求.(或者放在数组中,从后往前遍历)
无容器策略:
对于节点个数为奇数个的链表:
首先: 1->2->3->4->5
首先我们先找到中节点 就是->节点3
然后逆序使链表变成这样: 1->2->3<-4<-5
节点3的next指向空,这样就能从前往后遍历,知道两个引用相等
节点个数为偶数的链表我们取上中点视为中点开始逆序,直到 前面的引用指向了null
public static boolean isPalindrome(Node head){
if(head==null || head.next==null){
return true;
}
Node fast = head;
Node slow = head;
while(fast.next!=null && fast.next.next!=null){
fast = fast.next.next;
slow = slow.next;
}
Node prev = null;
Node next = null;
Node cur = slow;
while(cur!=null){
next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
fast = prev;
slow = head;
while(slow!=null && fast!=slow){
if(slow.val!= fast.val){
return false;
}else{
slow = slow.next;
fast = fast.next;
}
}
return true;
}