zoukankan      html  css  js  c++  java
  • leetcode 234 回文链表

    题目

    请判断一个链表是否为回文链表。

    解题思路

    反转链表的后半段。

    C++代码

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        bool isPalindrome(ListNode* head) {
            if(head == NULL || head->next == NULL)
                return true;
            ListNode* slow = head;
            ListNode* fast = head;
            while(fast->next)
            {
                slow = slow->next;
                fast = fast->next;
                if(fast->next)
                    fast = fast->next;
            }
            fast = slow->next;
            slow->next = NULL;
            while(fast)
            {
                ListNode *p = fast->next;
                fast->next = slow;
                slow = fast;
                fast = p;
            }
            fast = slow;
            slow = head;
            while(slow && fast)
            {
                if(slow->val != fast->val)
                    return false;
                fast = fast->next;
                slow = slow->next;
            }
            return true;
        }
    };
  • 相关阅读:
    学习进度条
    学术诚信与职业道德
    czxt
    操作系统
    04 17评论博客
    0414 结对 2.0 33 34
    0408 汉堡包
    (补)结对心得
    构建之法4读后感
    复利计算4.0
  • 原文地址:https://www.cnblogs.com/xumaomao/p/11364244.html
Copyright © 2011-2022 走看看