CC13:回文链表
题目
请编写一个函数,检查链表是否为回文。
给定一个链表ListNode* pHead,请返回一个bool,代表链表是否为回文。
测试样例:
{1,2,3,2,1}
返回:true
{1,2,3,2,3}
返回:false
解法
想法是这样,找到链表的中点,从中点之后的链表数据用栈进行存储;然后从链表的头部开始依次遍历直到中点处,每一次遍历都与栈的top进行比较,如果不相等就证明不是回文链表。这样的理解其实很简单,就是链表的后半部分通过栈编程反向的,从栈里依次取出的数据与链表首部到中点数据的顺序是一样的话,就说明是回文链表。代码如下:
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};*/
class Palindrome {
public:
bool isPalindrome(ListNode* pHead) {
// write code here
if(pHead==NULL)
return true;
ListNode *pFast=pHead;
ListNode *pSlow=pHead;
ListNode *temp=pHead;
int cnt=0;
while(pFast->next!=NULL && pFast->next->next!=NULL)
{
pSlow=pSlow->next;
pFast=pFast->next->next;
}
while(pSlow->next!=NULL)
{
res.push(pSlow->val);
cnt++;
}
for(int i=0;i<cnt;i++)
{
int t=res.top();
if(temp->val!=t)
return false;
temp=temp->next;
res.pop();
}
return true;
}
private:
stack<int> res;
};
但是报错显示超过限制的内存,证明应该不能用栈这个方式进行存储,可能需要对链表进行逆序.所以将利用栈的方法稍加修改改成对链表进行逆序,果然OK了,代码如下:
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};*/
class Palindrome {
public:
ListNode *reverse(ListNode *head) {
if(head == NULL)
return NULL;
ListNode *Next = head->next;
head->next = NULL;
while(Next != NULL)
{
ListNode *tmp = Next->next;
Next->next = head;
head = Next;
Next = tmp;
}
return head;
}
bool isPalindrome(ListNode* pHead) {
// write code here
if(pHead==NULL)
return true;
ListNode *pFast=pHead;
ListNode *pSlow=pHead;
ListNode *temp=pHead;
while(pFast->next!=NULL && pFast->next->next!=NULL)
{
pSlow=pSlow->next;
pFast=pFast->next->next;
}
pSlow->next=reverse(pSlow->next);
while(pSlow->next!=NULL)
{
pSlow=pSlow->next;
if(temp->val!=pSlow->val)
return false;
temp=temp->next;
}
return true;
}
};
这里值得注意一下的是逆序操作链表Reverse这个操作,看一下他函数是具体的操作:
作者:YunLambert
-------------------------------------------
个性签名:一名会音乐、爱健身的不合格程序员
可以Follow博主的Github哦(っ•̀ω•́)っ✎⁾⁾