题目:
给定一个链表的头节点head,请判断该链表是否为回文结构。例如:1->2->1,返回true。1->2->2->1,返回true。1->2->3,返回false。
进阶:如果链表长度为N,时间复杂度达到O(N),额外的空间复杂度达到O(1).
就直接来额外空间O(1)的方法吧:
设置两个指针,快指针一次走两步,慢指针一次走一步,快指针走完的时候,慢指针刚好打到中点
然后把后半部分逆序
然后从两边开始,每次同时走一步,看一不一样,有不一样返回false
#include<iostream>
#include<vector>
#include<algorithm>
#include<stack>
using namespace std;
class isPalindromeList{
public:
struct Node{
int value;
Node *next;
Node(int data,Node *ptr){
value=data;
next=ptr;
}
};
//need n extra space
bool isPalindrome1(Node head){
stack<Node>help;
Node cur=head;
while(cur.next!= nullptr){
help.push(cur);
cur=Node(cur.next->value,cur.next->next);
}
while(head.next!= nullptr){
if(head.value!=help.top().value){
return false;
}
help.pop();
head=Node(head.next->value,head.next->next);
}
return true;
}
//need n/2 extra space
bool isPalindrome2(Node head){
if(head.next== nullptr){
return true;
}
Node right=Node(head.value,head.next);
Node cur=head;
while(cur.next!= nullptr&&cur.next->next!= nullptr){
right=Node(right.next->value,right.next->next);
cur=Node(cur.next->next->value,cur.next->next->next);
}
stack<Node>help;
while (right.next!= nullptr){
help.push(right);
right=Node(right.next->value,right.next->next);
}
while(!help.empty()){
if(head.value!=help.top().value)
return false;
head=Node(head.next->value,head.next->next);
help.pop();
}
return true;
}
//need O(1) extra space
public bool isPalindrome3(Node head){
if(head.next== nullptr)
return true;
Node n1=head;
Node n2=head;
//find mid node
while(n2.next!= nullptr&&n2.next->next!= nullptr){
n1=Node(n1.next->value,n1.next->next);//n1->mid
n2=Node(n2.next->next->value,n2.next->next->next);//n2->end
}
//n2->right part first node
n2=Node(n1.next->value,n2.next->next);
n1.next= nullptr;//mid.next->null
Node n3(0, nullptr);
while(n2.next!= nullptr){//right part convert
n3=Node(n2.next->value,n2.next->next);//save next node
n2.next=&n1;//next of right node convert
n1=n2;//n1 move
n3=n2;//n2 move
}
n3=n1;//n3->save last node
n2=head;//n2->left first node
bool res=true;
while(n1.next!= nullptr&&n2.next!= nullptr){
if(n1.value!=n2.value){
res=false;
break;
}
n1=*n1.next;
n2=*n2.next;
}
n1=*n3.next;
n3.next= nullptr;
while(n1.next!= nullptr){//recover list
n2=*n1.next;
n1.next=&n3;
n3=n1;
n1=n2;
}
return res;
}
};