給定一個鏈表,請判斷該鏈表是否為回文結(jié)構(gòu)。
回文是指該字符串正序逆序完全一致。
數(shù)據(jù)范圍: 鏈表節(jié)點數(shù) 0≤n≤10^5
鏈表中每個節(jié)點的值滿足 ∣val∣≤10^7
# 示例1
輸入:{1}
返回值:true
# 示例2
輸入:{2,1}
返回值:false
說明:2->1
# 示例3
輸入: {1,2,2,1}
返回值:true
說明:1->2->2->1
/* struct ListNode {
* int val;
* struct ListNode *next;
* };
*
* C語言聲明定義全局變量請加上static,防止重復定義
*/
/**
*
* @param head ListNode類 the head
* @return bool布爾型
*/
bool isPail(struct ListNode* head ) {
// write code here
struct ListNode* pfast; //快指針
struct ListNode* pslow;//慢指針
struct ListNode* pnex;//后面一個指針
pfast = head;
pslow = head;
pnex = NULL;
if(head==NULL || head->next==NULL)
{
return true;
}
while(pfast!=NULL && pfast->next!=NULL)
{
pfast = pfast->next->next;
pslow = pslow->next;
}
pfast = pslow->next;
pslow->next=NULL;
while(pfast!=NULL)
{
pnex = pfast->next;
pfast->next = pslow;
pslow = pfast;
pfast = pnex;
}
pfast = head;
while(pslow!=NULL && pfast!=NULL)
{
if(pslow->val!=pfast->val)
{
return false;
}
pfast = pfast->next;
pslow = pslow->next;
}
return true;
//只要循環(huán)n/2次
// for(int i=0;i<(n/2);i++)
// {
// j = 0;
// while(j<(n-i-1))
// {
// p2 = p2->next;
// j++;
// }
// if(p1->val == p2->val)
// {
// p1 = p1->next;
// p2 = head;
// }
// else
// {
// return false;
// }
// }
}