回文链表
请判断一个链表是否为回文链表。
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
(1)用数组存储,然后用数组比较。
/** * 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) { if(head == NULL || head->next == NULL){ return true; } vector<int> vec; ListNode *r = head; int len = 0; while(r != NULL){ vec.push_back(r->val); r = r->next; len++; } for(int i = 0; i < len/2; i++){ if(vec[i] != vec[len-1-i]){ return false; } } return true; } };
(2)递归
class Solution { public: ListNode *f; bool isPalindrome(ListNode* head) { if(head == NULL || head->next == NULL){ return true; } f = head; return check(head); } bool check(ListNode *p){ if(p->next != NULL){ if(!check(p->next)){ return false; } if(f->val != p->val){ return false; } } f = f->next; return true; } };
(3)双指针找中间+反转后半部分
class Solution { public: ListNode *f; bool isPalindrome(ListNode* head) { if(head == NULL || head->next == NULL){ return true; } ListNode *s = head; ListNode *f = head->next; while(f != NULL && f->next != NULL){ s = s->next; f = f->next->next; } ListNode *reverseHead = reverseList(s->next); s = head; f = reverseHead; while(f != NULL){ if(s->val != f->val){ return false; } s = s->next; f = f->next; } return true; } ListNode* reverseList(ListNode* head) { if(head != NULL){ ListNode *p = head->next; ListNode *q = head; while(p != NULL){ q->next = p->next; p->next = head; head = p; p = q->next; } } return head; } };