判断回文链表的4种做法,递归,栈,反转链表,和把链表转为数组使用双指针进行判断数组回文 leetcode234题回文链表

判断回文链表的几种做法,递归,栈,反转链表,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的做法

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值