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;
}
};