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;
    }
};
相关文章
|
1天前
|
算法 Java C语言
【经典算法】LeetCode25:K 个一组翻转链表(Java/C/Python3,Hard)
【经典算法】LeetCode25:K 个一组翻转链表(Java/C/Python3,Hard)
5 1
|
9天前
题目----力扣--回文链表
题目----力扣--回文链表
18 0
|
9天前
题目----力扣--合并两个有序链表
题目----力扣--合并两个有序链表
13 0
|
9天前
题目----力扣--反转链表
题目----力扣--反转链表
17 0
|
9天前
题目----力扣--链表的中间结点
题目----力扣--链表的中间结点
7 0
|
9天前
题目----力扣--移除链表元素
题目----力扣--移除链表元素
15 1
|
10天前
<数据结构>五道LeetCode链表题分析.环形链表,反转链表,合并链表,找中间节点.
<数据结构>五道LeetCode链表题分析.环形链表,反转链表,合并链表,找中间节点
20 1
|
10天前
|
索引
【力扣刷题】删除链表的倒数第 N 个结点、两两交换链表中的节点、随机链表的复制
【力扣刷题】删除链表的倒数第 N 个结点、两两交换链表中的节点、随机链表的复制
17 0
|
22天前
|
算法
LeetCode刷题---19. 删除链表的倒数第 N 个结点(双指针-快慢指针)
LeetCode刷题---19. 删除链表的倒数第 N 个结点(双指针-快慢指针)
|
22天前
【移除链表元素】LeetCode第203题讲解
【移除链表元素】LeetCode第203题讲解