[leetcode] Palindrome Linked List
2015-08-12 10:47
162 查看
题目链接在此
Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?
要求用O(N)的时间和O(1)的空间,判断单链表是否为回文串。
可以用一快一慢两个链表,溜一遍,寻找到链表的中点。
然后将后半段翻转,与前半段对比,看是否相同,进而判断是否为回文串。
Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?
要求用O(N)的时间和O(1)的空间,判断单链表是否为回文串。
可以用一快一慢两个链表,溜一遍,寻找到链表的中点。
然后将后半段翻转,与前半段对比,看是否相同,进而判断是否为回文串。
struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: bool isPalindrome(ListNode* head) { if (head == NULL || head->next == NULL) return true; ListNode* slow = head; // 慢指针,一次走一步 ListNode* fast = head; // 快指针,一次走两步 ListNode* originalHead = head; // 当快指针走到链表尽头的时候,慢指针恰好到达链表中点。 while (fast->next != NULL && fast->next->next != NULL) { slow = slow->next; fast = fast->next->next; } slow = slow->next; // 后半段的起点 ListNode* reverseHead = reverseList(slow); // 翻转后半段 return cmp(originalHead, reverseHead); // 比较前、后半段是否相同 } private: ListNode* reverseList(ListNode* head) { // 反转以head为头的单链表,并返回新的头指针(即原来的尾指针) if (head == NULL || head->next == NULL) return head; ListNode *p = head; ListNode *q = head->next; ListNode *r = head->next->next; head->next = NULL; while (true) { q->next = p; p = q; q = r; if (r != NULL) r = r->next; else break; }; return p; } bool cmp(ListNode* h1, ListNode* h2) { while (h1 != NULL && h2 != NULL) { if (h1->val != h2->val) return false; h1 = h1->next; h2 = h2->next; } return true; } };
相关文章推荐