回文链表
什么是回文?举两个栗子
上海自来水来自海上
黄山落叶松叶落山黄
如何判断链表是不是回文呢?
- 找到链表的中间节点
- 将链表后半部分反转
- 比较链表前半部分和后半部分是否相同
struct ListNode { char value; ListNode *next; }; ListNode* getMiddleNode(ListNode *head) { if(head == NULL || head->next == NULL) return head; ListNode *fast = head; ListNode *slow = head; while (fast->next != NULL) { fast = fast->next; slow = slow->next; if(fast->next != NULL) fast = fast->next; } return slow; } ListNode* reverseListRecursive(ListNode *head) { if(head == NULL || head->next == NULL) return head; ListNode *newHead = reverseListRecursive(head->next); head->next->next = head; head->next = NULL; return newHead; } bool isPalindrome(ListNode *head) { if (head == NULL || head->next == NULL) return true; ListNode *middleNode = getMiddleNode(head); ListNode *rbegin = reverseListRecursive(middleNode); ListNode *lbegin = head; while (rbegin != NULL) { if (lbegin->value != rbegin->value) { return false; } lbegin = lbegin->next; rbegin = rbegin->next; } return true; }
完美。