[LeetCode]234. Palindrome Linked List 解题报告(C++)

[LeetCode]234. Palindrome Linked List 解题报告(C++)

题目描述

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

Example 1:

Input: 1->2
Output: false

Example 2:

Input: 1->2->2->1
Output: true

Follow up:
Could you do it in O(n) time and O(1) space?

题目大意

  • 检查给定的单链表是否是 回文
  • 时间复杂度 O(n) 空间复杂度O(1)

解题思路

方法1:

  • 通过 栈存储前一半. 用快慢指针遍历一半.
  • 遍历后面一半.. 从栈中取出看是否与后面一半的相同
  • 空间复杂度并非 O(1)
代码实现:
class Solution {
public:
    bool isPalindrome(ListNode* head) {

        if (!head || !head->next) return true;

        ListNode *slow, *fast;
        slow = head; fast = head;
        stack<int> s;
        while (fast&&fast->next) {
            s.push(slow->val);
            slow = slow->next;
            fast = fast->next->next;
        }
        if (fast) {
            while (slow->next) {
                slow = slow->next;
                int tmp = s.top(); s.pop();
                if (tmp != slow->val) {
                    return false;
                }
            }
        }
        else {
            while (slow) {
                int tmp = s.top(); s.pop();
                if (tmp != slow->val) {
                    return false;
                }
                slow = slow->next;
            }
        }
        return true;
    }
};

方法2:

  • reverse链表.

代码实现:

class Solution {
public:
    bool isPalindrome(ListNode* head) {
        if(head==NULL||head->next==NULL)
            return true;
        ListNode* slow=head;
        ListNode* fast=head;
        while(fast->next!=NULL&&fast->next->next!=NULL){
            slow=slow->next;
            fast=fast->next->next;
        }
        slow->next=reverseList(slow->next);
        slow=slow->next;
        while(slow!=NULL){
            if(head->val!=slow->val)
                return false;
            head=head->next;
            slow=slow->next;
        }
        return true;
    }
    ListNode* reverseList(ListNode* head) {
        ListNode* pre=NULL;
        ListNode* next=NULL;
        while(head!=NULL){
            next=head->next;
            head->next=pre;
            pre=head;
            head=next;
        }
        return pre;
    }
};

小结

  • 这一题有一个疑问!!!
  • 翻转链表的空间复杂度到底是 O(n) 还是 O(1)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值