首页 > 其他 > 详细

234 Palindrome Linked List 回文链表

时间:2018-04-09 14:30:30      阅读:145      评论:0      收藏:0      [点我收藏+]

请检查一个链表是否为回文链表。

进阶:
你能在 O(n) 的时间和 O(1) 的额外空间中做到吗?

详见:https://leetcode.com/problems/palindrome-linked-list/description/

方法一:

/**
 * 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==nullptr||head->next==nullptr)
        {
            return true;
        }
        ListNode *slow=head;
        ListNode *fast=head;
        stack<int> stk;
        stk.push(head->val);
        while(fast->next&&fast->next->next)
        {
            slow=slow->next;
            fast=fast->next->next;
            stk.push(slow->val);
        }
        if(!fast->next)
        {
            stk.pop();
        }
        while(slow->next)
        {
            slow=slow->next;
            int tmp=stk.top();
            if(slow->val!=tmp)
            {
                return false;
            }
            stk.pop();
        }
        return true;
    }
};

方法二:

/**
 * 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||!head->next)
        {
            return true;
        }
        ListNode *slow=head;
        ListNode *fast=head;
        ListNode *first=nullptr;
        while(fast&&fast->next)
        {
            first=slow;
            slow=slow->next;
            fast=fast->next->next;
        }
        fast=first->next;
        first->next=nullptr;
        ListNode *pre=nullptr;
        ListNode *next=nullptr;
        while(fast)
        {
            next=fast->next;
            fast->next=pre;
            pre=fast;
            fast=next;
        }
        first=head,fast=pre;
        while(first&&fast)
        {
            if(first->val!=fast->val)
            {
                return false;
            }
            first=first->next;
            fast=fast->next;
        }
        return true;
    }
};

参考:https://www.cnblogs.com/grandyang/p/4635425.html

234 Palindrome Linked List 回文链表

原文:https://www.cnblogs.com/xidian2014/p/8759212.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!