234.回文链表()

给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。

输入:head = [1,2,2,1]
输出:true

不能用反转链表,因为链表只有一条,反转之后还是那一条,并没有复制新的一条链表,是错误做法,除非自己花精力自己再复制一下这个链表。

方法一:将值复制在数组中再采用双指针(因为链表只能单向遍历,不能双向遍历)

class Solution {
public:
    bool isPalindrome(ListNode* head) {
        if(head == NULL )  return false;
        vector<int> vals;
        while(head != NULL){
            vals.push_back(head -> val);
            head = head -> next;
        }
        
        for(int i = 0 , j = vals.size() -1 ; i < vals.size() ; i++ , j--){
            if(vals[i] != vals[j]) return false;
        }
        return true;
    }
};

方法二:递归(和反转不一样,递归式用一个全局变量存链表的头节点,然后和归的节点比较)

要点: if(!reserveList(head -> next))  归的布尔,将归作为一种判断而不是返回头节点。,因为不需要知道这个链表的尾节点。

只要有一个相等,直接全部都是false返回,如果相等,则一直返回true

class Solution {
public:
    ListNode* frontPoint;
    bool isPalindrome(ListNode* head) {
        if(head == NULL )  return false;
        frontPoint = head;
        return reserveList(head);
    }
    bool reserveList(ListNode* head){
        if(head != NULL){
        if(!reserveList(head -> next)) return false;
        if(frontPoint -> val != head -> val) return false;
        frontPoint = frontPoint -> next;
        }
        return true;
    }
};

方法三:栈(利用先进后出得原则)

class Solution {
public:
    bool isPalindrome(ListNode* head) {
        if(head == NULL )  return false;
        stack<int> stack;
        ListNode* newhead = head ;
        while(head != NULL){
            stack.push(head -> val);
            head = head -> next;
        }
        while(!stack.empty()){
            if(stack.top() != newhead -> val) return false;
            stack.pop();
            newhead = newhead -> next;
        }
        return true;
    }

};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值