回文链表002

1、描述

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

示例 1:

输入: 1->2
输出: false
示例 2:

输入: 1->2->2->1
输出: true

2、关键字

链表、回文

3、思路

1、前后对应,栈把后边一半存起来,队列把前边一半存起来,
然后比较
2、分奇偶情况

4、notes

1、while(真假?)
if(真假?)
2、如果是奇数,链表在从前一半到后一半过渡时,中间需要踩空一步
3、解析说,转存到数组中,可以把空间复杂度变成O(1)
4、head指针到最后,没回来。!!!
Line 32: Char 39: runtime error: member access within null pointer of type ‘ListNode’ (solution.cpp)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:36:39

5、复杂度

时间:O(N)
空间:O(N)

6、code

/**
 * 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) return true;
        bool flag=true;
        queue<int> left;
        stack<int>right;
            int longth=0;
            auto tem=head;  // 保存头节点,如果直接用头节点往后遍历,那遍历一遍之后就找不到头节点了
            while(tem){
                longth++;
                tem=tem->next;
            }
/*
这个错
Line 32: Char 39: runtime error: member access within null pointer of type 'ListNode' (solution.cpp)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:36:39

*/

            if(longth==1) return true;  // 防止后面的+2,出现问题
             tem=head;  // 
            if(longth%2==0){  // 偶数
                for(int i=1;i<=longth/2;i++)
                {
                    left.emplace(tem->val);
                    tem=tem->next;
                }
                for(int j=longth/2+1;j<=longth;j++)
                {
                    right.push(tem->val);
                    tem=tem->next;
                }
            }
             else if(longth%2==1){
                for(int i=1;i<=longth/2;i++)
                {
                    left.push(tem->val);
                    tem=tem->next;
                }
                tem=tem->next;// 这里肯定需要把链表往后挪动一步,因为奇数跳了一下
                for(int j=longth/2+2;j<=longth;j++)
                {
                    right.push(tem->val);
                    tem=tem->next;
                }
            }
            for(int i=0;i<longth/2;i++)
            {
                if(left.front()==right.top())
                {
                    left.pop();
                    right.pop();
                }
                else
                {
                    flag=false;
                    break;
                }
            }
            return flag;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值