234. Palindrome Linked List
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?
Subscribe to see which companies asked this question
一个用stack 存的版本
/** * 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; } //定义快慢指针 ListNode *fast=head; ListNode *slow=head; //只有当fast->next->next存在,才继续下移,保证了跳出while循环时,slow->next指向后半部分 while(fast->next && fast->next->next){ fast=fast->next->next; slow=slow->next; } /* while循环结束后,slow 指针和fast 指针的指向情况如下 eg: 1->2->3->4->NULL 需要对3,4 入栈 ^ ^ | | slow fast 1->2->3->4->5->NULL 需要对4,5入栈 ^ ^ | | slow fast 所以用slow表示需要入栈的后半部分头结点,需要将slow下移一位 */ slow=slow->next; stack<int> S; //建栈 while(slow!=NULL){//将以slow为头结点的链表节点值压入栈 S.push(slow->val); slow=slow->next; } /* 开始比较 eg : 1->2->2->1->NULL ^ | head S.top() 1 2 */ while(S.size()>0){ //栈不为空 if(S.top()!=head->val){ //只要遇到不相等的,return false; return false; } head=head->next; S.pop(); } return true; } };