Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Definition for singly-linked list.
- * struct ListNode {
- * int val;
- * ListNode *next;
- * ListNode() : val(0), next(nullptr) {}
- * ListNode(int x) : val(x), next(nullptr) {}
- * ListNode(int x, ListNode *next) : val(x), next(next) {}
- * };
- */
- class Solution
- {
- public:
- ListNode* mid(ListNode* head)
- {
- ListNode* s=head,*f=head;
- while(f && f->next)
- {
- s=s->next;
- f=f->next;
- if(f) f=f->next;
- }
- return s;
- }
- ListNode* reverse(ListNode* head)
- {
- ListNode* prev=NULL,*cur=head,*next=NULL;
- while(cur)
- {
- next=cur->next;
- cur->next=prev;
- prev=cur;
- cur=next;
- }
- cur=prev;
- return cur;
- }
- bool cmp(ListNode* a,ListNode* b)
- {
- while(a && b)
- {
- if(a->val != b->val) return false;
- a=a->next;
- b=b->next;
- }
- return true;
- }
- bool isPalindrome(ListNode* head)
- {
- if(!head || !head->next) return true;
- ListNode* h=head;
- ListNode* m = mid(h);
- ListNode* h1=reverse(m);
- return cmp(head,h1);
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement