题解 | #牛群编号的回文顺序#

牛群编号的回文顺序

https://www.nowcoder.com/practice/e41428c80d48458fac60a35de44ec528

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 
     * @return bool布尔型
     */

     //用栈存一半然后出栈比较另一半
    bool isPalindrome(ListNode* head) {
        // write code here

        if(!head) return false;
        if(!head->next) return true;
        std::stack<ListNode*> s;
        int i=0;
        ListNode *p=head;
        while(p){ //统计有多少节点
            i++;
            p=p->next;
        }
        p=head;
        int j=i/2;
        while(j--){
            s.push(p);
            p=p->next;
        }
        if(i%2){
            p=p->next;
        }
        j=i/2;
        while(j--){
            if(s.top()->val!=p->val) return false;
            cout<<p->val<<','<<s.top()->val<<"--";
            s.pop();
            p=p->next;
        }
        if(!s.empty()||p) return false;

        return true;
    }
};

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务