1.用栈
class Solution {
public:
bool isPalindrome(ListNode* head) {
stack<ListNode*>st;
ListNode*cur1=head;
ListNode*cur2=head;
while(cur1){
st.push(cur1);
cur1=cur1->next;
}
while(cur2){
ListNode*popNode=st.top();
st.pop();
if(popNode->val!=cur2->val) return false;
cur2=cur2->next;
}
return true;
}
};
2.用栈和快慢指针
class Solution {
public:
bool isPalindrome(ListNode* head) {
stack<ListNode*>st;
ListNode*slow=head;
ListNode*fast=head;
if(head==NULL) return true;
while(fast->next!=NULL&&fast->next->next!=NULL){
st.push(slow);
slow=slow->next;
fast=fast->next->next;
}
// 此时若整个链表为双数,slow指向上一半的最后一个,需要入栈slow
// 若为单数,指向中间元素,不需要入栈slow
// 单双数的判断由quick的终止条件确定
if (fast->next!=NULL) {
st.push(slow);
}
slow=slow->next;
while(!st.empty()){
ListNode*popNode=st.top();
st.pop();
if(popNode->val!=slow->val) return false;
slow=slow->next;
}
return true;
}
};
3.快慢指针和反转链表
public class Main {
public static boolean process(Node header) {
if (header == null) {
return false;
}
Node slow = header;
Node quick = header;
while (quick.next != null && quick.next.next != null) {
slow = slow.next;
quick = quick.next.next;
}
slow=slow.next;
Node preNode=null;
Node postNode=null;
// 后半段反转
while (slow!=null) {
preNode=slow.next;
slow.next=postNode;
postNode=slow;
slow=preNode;
}
Node tailLeft=header;
Node tailRight=postNode;
boolean flag=true;
// 两边向中间判断
while (tailRight!=null) {
if (tailLeft.value!=tailRight.value) {
flag=false;
break;
}
tailLeft=tailLeft.next;
tailRight=tailRight.next;
}
Node tailNode=null;
// 后半段链表恢复
while (postNode!=null) {
preNode=postNode.next;
postNode.next=tailNode;
tailNode=postNode;
postNode=preNode;
}
return flag;
}
public static class Node {
int value;
Node next;
}
}