LeetCode 027.回文链表 C写法
思路🧐:
快慢指针+反转链表,通过快慢指针找到中间结点,再将中间结点后的所有结点反转。如果是回文链表那么中间结点往后的值与头结点到中间结点的值都相等,如果有不相等的就不是回文链表。
代码✨:
c
struct ListNode* MidNode(struct ListNode* head) //找中间结点
{
struct ListNode* fast = head;
struct ListNode* slow = head;
while(fast && fast->next)
{
fast = fast->next->next;
slow = slow->next;
}
return slow;
}
struct ListNode* Reverse(struct ListNode* midhead) //链表反转
{
struct ListNode* rhead = NULL;
struct ListNode* cur = midhead;
while(cur)
{
struct ListNode* tail = cur->next;
cur->next = rhead;
rhead = cur;
cur = tail;
}
return rhead;
}
bool isPalindrome(struct ListNode* head){
struct ListNode* cur = head;
struct ListNode* mid = MidNode(head);
struct ListNode* midhead = Reverse(mid);
while(cur != mid) //当cur走到mid结点处就结束
{
if(cur->val != midhead->val) //如果不相等就返回false
{
return false;
}
else //如果相等就继续往后走
{
cur = cur->next;
midhead = midhead->next;
}
}
return true;
}