leetcode 234 回文链表

简介: leetcode 234 回文链表

回文链表

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    bool isPalindrome(ListNode* head) {
        stack<int> mystack;
        int node_num = 0;
        ListNode *tmp = head;
        while(tmp != nullptr)
        {
            tmp = tmp->next;
            node_num ++;
        }
        tmp = head;
        for(int i=1 ; i<=node_num ;i++)
        {
            if(i<=node_num/2) mystack.push(tmp->val);
            if(i>node_num/2+node_num%2)
            {
                if(tmp->val != mystack.top()) return false;
                mystack.pop();
            } 
            tmp = tmp->next;
        }
        return true;
    }
};
相关文章
|
6天前
LeetCode链表hard 有思路?但写不出来?
LeetCode链表hard 有思路?但写不出来?
|
6天前
|
索引
每日一题:力扣328. 奇偶链表
每日一题:力扣328. 奇偶链表
14 4
|
6天前
leetcode代码记录(移除链表元素
leetcode代码记录(移除链表元素
11 0
【每日一题】LeetCode——反转链表
【每日一题】LeetCode——反转链表
【每日一题】LeetCode——链表的中间结点
【每日一题】LeetCode——链表的中间结点
|
6天前
|
C++
[leetcode 链表] 反转链表 vs 链表相交
[leetcode 链表] 反转链表 vs 链表相交
|
6天前
【力扣】148. 排序链表
【力扣】148. 排序链表
|
6天前
|
索引
【力扣】142. 环形链表 II
【力扣】142. 环形链表 II
|
6天前
【力扣】19. 删除链表的倒数第 N 个结点
【力扣】19. 删除链表的倒数第 N 个结点
|
6天前
|
算法 C++
【刷题】Leetcode 1609.奇偶树
这道题是我目前做过最难的题,虽然没有一遍做出来,但是参考大佬的代码,慢慢啃的感觉的真的很好。刷题继续!!!!!!
9 0

热门文章

最新文章