Mi informacion de contacto
Correo[email protected]
2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
思路🧐:
puntero de velocidad+Lista enlazada inversa , Encuentre el nodo intermedio a través de los punteros rápido y lento, y luego invierta todos los nodos después del nodo intermedio. Si es una lista enlazada de palíndromo, entonces los valores del nodo intermedio al nodo intermedio son iguales a los valores del nodo principal al nodo intermedio. Si hay valores desiguales, no es una lista enlazada de palíndromo. .
Código ✨:
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;
}