The requirement of this topic is to determine whether a single linked list is a palindrome list, the difficulty of the topic is O (n) time and O (1) space limitations.
Because the single-linked list can not be reversed, so can not directly through the original linked list to judge, the idea is to solve the original list of the first half of the list to judge, and then to judge (such as the list of "12344321" after the reversal of "43214321"). The realization after this is very simple, and the complete code looks like this:
Class Solution {public:listnode* reversehalf (listnode* root) {ListNode *fast = root, *slow = Root;//slow points to the reverse section of the latter node while (fast! = nullptr && fast-and next! = nullptr) {fast = fast-Next-& Gt Next slow = slow next; } ListNode *h = new ListNode (0); H-Next = root;//performs reverse listnode *sec = root, *fir = root-Next; while (fir! = Slow) {sec-next = fir-next; Fir-Next = h-Next; H-next = Fir; Fir = sec-Next; } return h-next; } bool Ispalindrome (listnode* head) {int len = 0; listnode* p = head; ListNode *fast, *slow;//calculates the length of the single-linked list while (P! = NULL) {len++; p = p and next; } if (Len < 2) return true;//reverses the first half of the single-linked list listnode* reversedlist = Reversehalf (head); Slow point to the middle position of the single-linked list Fast = slow = reversedlist; while (fast! = nullptr && fast-next! = nullptr) {fast = fast-next Next; slow = slow next; }//fast points to the head of a single-linked list fast = Reversedlist; if (len% 2 = 0) slow = slow-next;//to determine if it is a palindrome string while (slow! = nullptr) {if (Fast, VA L! = Slow val) return false; Fast = fast-next; slow = slow next; } return true; }};
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Palindrome Linked List