Leetcode Palindrome Linked List

Leetcode Palindrome Linked List 这个题目相对简单,回文串的相关题目我们也见过很多,本题要求在o(n)的时间,与o(1)的空间完成,在链表中还是有一定的思考价值的,相关代码如下,并给出测试:

#include<iostream>

using namespace std;

//Definition for singly-linked list.
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

// First count the num of the node
// Reverse the pre num / 2 node
// Compare the node val for the centre to the edge
// the time complex is O(n), and the space complex O(1)
class Solution {
public:
    bool isPalindrome(ListNode* head) {
        int count = 0;
        int reverse_count = 0;
        ListNode* cur = head;
        ListNode* pre;
        ListNode* next;
        ListNode* cur_re;
        // Count the number of the node
        while (cur != NULL) {
            cur = cur->next;
            count ++;
        }
        reverse_count = count / 2;
        cur = head;
        pre = NULL;
        // Reverse the first count / 2 node
        while (reverse_count != 0) {
            next = cur->next;
            cur->next = pre;
            pre = cur;
            cur = next;
            reverse_count --;
        }
        cur_re = pre;
        cur = count % 2 == 0? cur: cur->next;
        // Compare the node val from the center to the edge
        while (cur != NULL) {
            if (cur->val != cur_re->val) {
                return false;
            }
            cur = cur->next;
            cur_re = cur_re->next;
        }
        return true;
    }
};

int main(int argc, char* argv[]) {
    ListNode* l = new ListNode(0);
    ListNode* cur = l;
    cur->next = new ListNode(1);
    cur = cur->next;
    cur->next = new ListNode(1);
    cur = cur->next;
    cur->next = new ListNode(0);
    cur = cur->next;
    Solution so;
    bool re = so.isPalindrome(l);
    cout<<"result: "<<re<<endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值