struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
bool isPalindrome(ListNode* head)
{
int lenth, i;
ListNode *point1, *point2, *point3;
point3 = point2 = head;
point1 = NULL;
lenth = 0;
if(head == NULL || head->next == NULL)
return true;
while(point3 != NULL)//取得长度
{
point3 = point3->next;
lenth++;
}
for(i = 0;i < (lenth / 2);i++)//遍历到中间,并逆置 1 <- 2 <- 3 -> 2 -> 1
{
point3 = point2->next;
point2->next = point1;
point1 = point2;
point2 = point3;
}
if((lenth % 2) == 1)
point3 = point3->next;
//两个指针从中间开始向两头移动,取值比较
//若需要将链表结构改为原来结构,则只需在判断的时候进行反转即可
while(point3 != NULL && point1 != NULL)
{
if(point3->val != point1->val)
return false;
point3 = point3->next;
point1 = point1->next;
}
return true;//比较中没有发现不同值,则为回文链表
}
};
LeetCode 回文链表(遍历过程中逆置一半的链表)
最新推荐文章于 2022-11-20 12:42:14 发布