标签:ret isp link ems rom fast leetcode while info
请判断一个链表是否为回文链表。
来源:力扣(LeetCode)
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: bool isPalindrome(ListNode* head) { // 1.快慢指针找到中点 ListNode* slow = head; ListNode* fast = head; while (fast != nullptr && fast->next != nullptr) { slow = slow->next; fast = fast->next->next; } // 偶数节点, 慢指针走到中点 if (fast != nullptr) slow = slow->next; // 2.反转后半部分链表 ListNode* prev = nullptr; while (slow != nullptr) { ListNode* temp = slow->next; slow->next = prev; prev = slow; slow = temp; } // 3.判断两个链表是否相等 while (head != nullptr && prev != nullptr) { if (head->val != prev->val) return false; head = head->next; prev = prev->next; } return true; } };
LeetCode 234. 回文链表 Palindrome Linked List (Easy)
标签:ret isp link ems rom fast leetcode while info
原文地址:https://www.cnblogs.com/ZSY-blog/p/12906641.html