【回文链表】leetcode234. 回文链表

链接:
题目:
给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。
在这里插入图片描述


解题:
方法1、利用快慢指针找到链表中点,然后逆链表,比较
方法2、利用堆栈

class Solution {
    
    
public:
    /**
     * 
     * @param head ListNode类 the head
     * @return bool布尔型
     */
    bool isPail(ListNode* head) {
    
    
        // write code here
        if(head==nullptr)return false;
        ListNode* last=head;
        ListNode* first=head;
        stack<int> lSt;
        while(last){
    
    
            lSt.push(last->val);
            last=last->next;
        }
        int n=lSt.size();
        for(int i=0;i<n/2;i++){
    
    
            int tmp=lSt.top();lSt.pop();
            if(first->val!=tmp){
    
    
                return false;
            }
            first=first->next;
        }
        return true;
    }
};

猜你喜欢

转载自blog.csdn.net/ryanji/article/details/127624281