给定一个链表的 头节点 head
,请判断其是否为回文链表。
如果一个链表是回文,那么链表节点序列从前往后看和从后往前看是相同的。
示例 1:
输入: head = [1,2,3,3,2,1] 输出: true
示例 2:
输入: head = [1,2] 输出: false
提示:
- 链表 L 的长度范围为
[1, 105]
0 <= node.val <= 9
此题的思路需巧妙运用到翻转链表的思想,
我们将后半链表翻转,再与前半链表进行比较,以此来判断回文结构的链表
首先我们运用快慢指针法来找到中间节点,然后翻转后半的链表,最后将后半链表的节点与前半链表的节点进行一一比较
bool isPalindrome(struct ListNode* head){
//找出链表的中间节点
struct ListNode* fast = head;
struct ListNode* slow = head;
while (fast && fast->next)
{
fast = fast->next->next;
slow = slow->next;
}
//翻转后半部分链表
struct ListNode* newhead = NULL;
struct ListNode* cur = slow;
while (cur)
{
struct ListNode* next = cur->next;
cur->next = newhead;
newhead = cur;
cur = next;
}
//比较前后半部分链表
struct ListNode* curA = head;
struct ListNode* curB = newhead;
while (curA && curB)
{
if (curA->val != curB->val)
{
return false;
break;
}
else
{
curA = curA->next;
curB = curB->next;
}
}
return true;
}
测试代码:
void test(SLTNode* plist)
{
bool is_palindrome = isPalindrome(plist);
if (is_palindrome)
{
printf("该链表为回文结构\n");
}
else
{
printf("该链表不是回文结构\n");
}
}