判断回文链表的几种做法,递归,栈,反转链表,leetcode234题回文链表
1.使用递归 ,比较复杂,要返回多个值,所以要重新定义一个类来返回
```C++
class back{
public:
back(bool ret,ListNode* node){
this->ret = ret;
this->node = node;
}
ListNode* node;
bool ret;
};
class Solution {
public:
back isHuiWen(ListNode* head,int start,int n)
{
if(start>n/2){
if(n%2==0){
return back(true,head);
}
return back(true,head->next);
}
back Back = isHuiWen(head->next,start+1,n);
if(Back.ret==false) return back(false,Back.node->next);
if(head->val != Back.node->val){
return back(false,Back.node->next);
}
return back(true,Back.node->next);
}
bool isPalindrome(ListNode* head) {
if(head==NULL || head->next==NULL) return true;
int len=1;
ListNode* tmp = head;
while(tmp->next){
tmp=tmp->next;
len++;
}
back Back = isHuiWen(head,1,len);//2
if(Back.ret==true) return true;
return false;
}
};
```
2.使用栈 ,栈和递归本质一样,但栈更清晰
```C++
class Solution {
public:
bool isPalindrome(ListNode* head) {
stack<ListNode*> st;
int len=0;
ListNode* tmp = head;
while(tmp){
tmp=tmp->next;
len++;
}
tmp=head;
for(int i=1;i<=len/2;i++){//栈中压入前n/2个元素
st.push(tmp);
tmp=tmp->next;
}
if(len%2==1){
tmp = tmp->next;
}//tmp指向要比较元素的开始位置
while(!st.empty()){
if(tmp->val!=st.top()->val){
return false;
}
tmp=tmp->next;
st.pop();
}
return true;
}
};
```
3.反转链表,空间复杂度为0n
```C++
class Solution {
public:
bool isPalindrome(ListNode* head) {
//反转链表的写法
ListNode* tmp =head;
int len = 0;
while(tmp){//得到长度
len++;
tmp=tmp->next;
}
ListNode* pre, *last;
//反转前len/2个
pre = NULL;
last = head;
for(int i=0;i<len/2;i++)
{
tmp = last->next;
last->next=pre;
pre = last;
last =tmp;
}
//pre为开始元素,last为后一个
if(len%2==1){//奇数向后一个开始比较
last=last->next;
}
while(last){
if(last->val!=pre->val){
return false;
}
last=last->next;
pre = pre->next;
}
return true;
}
};
```
使用递归最复杂,栈次之,时间空间均为0n,反转链表 ,反转前n/2个可得到时间0n空间01的做法
使用递归最复杂,栈次之,时间空间均为0n,反转链表 ,反转前n/2个可得到时间0n空间01的做法