zoukankan      html  css  js  c++  java
  • leetcode 234. Palindrome Linked List

    Given a singly linked list, determine if it is a palindrome.

    Follow up:
    Could you do it in O(n) time and O(1) space?
    判断一个链表是不是回文的。
    思路:遍历节点得到总数tot,然后反转链表的后半部分,再和前半部分比较。

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* head2 = nullptr;
        int tot = 0;
        int num = 0;
        void reverse(ListNode* p, ListNode* q) {
            if (p == nullptr) {
                head2 = q;
                return ;
            }
            reverse(p->next, p);
            if (q) q->next = nullptr;
            if (p) p->next = q;
        }
        bool isPalindrome(ListNode* head) {
            ListNode* p = head;
            ListNode* x = nullptr;
            ListNode* q = nullptr;
            while (p) {
                tot++;
                p = p->next;
            }
            p = head;
            while (p) {
                num++;
                if (num == tot/2) {
                    x = p;
                    break;
                }
                p = p->next;
            }
            reverse(x, nullptr);
            p = head;
            q = head2;
            while (p && q) {
                if (p->val != q->val) return false;
                p = p->next;
                q = q->next;
            }
            return true;
        }
    };
    
  • 相关阅读:
    MarkDown SequenceDiagram 语法
    mysql导出数据库文档
    使用gitlab作为go mod私服
    go context理解
    go-micro入门
    golang 接口测试
    小程序配置 app.json
    Nginx 配置详解(2)
    windows下安装nginx
    任意文件夹下打开命令提示窗
  • 原文地址:https://www.cnblogs.com/pk28/p/8485107.html
Copyright © 2011-2022 走看看