1、回文链表定义
前后对称
2、思路
快慢指针slow/fast
3、真的是改了不少bug,一定要主要指针要指的有意义
4、代码
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 bool isPalindrome(ListNode* head) { 12 ListNode *slow,*fast,*p;//p为了保留slow的位置 13 fast=head; 14 slow=head; 15 //if(head==NULL) return true;//第一次没考虑这种情况 16 //if(head!=NULL&&head->next==NULL) return true;//这种情况也没考虑 17 p=head; 18 if(head!=NULL&&head->next!=NULL){ 19 while(slow->next!=NULL&&fast->next!=NULL&&fast->next->next!=NULL){ 20 slow=slow->next; 21 p=p->next; 22 fast=fast->next->next; 23 } 24 if(fast->next!=NULL) { 25 slow=slow->next; 26 p=p->next; } 27 else{ 28 slow=slow->next; 29 } 30 while(slow!=NULL){ 31 q.push(slow->val); 32 slow=slow->next; 33 } 34 while(head!=p&&!q.empty()){ 35 if(head->val==q.top()){ 36 head=head->next; 37 q.pop(); 38 } 39 else{ 40 break;//跳出循环执行循环后面的语句,continue是结束本次循环,执行下一次循环 41 } 42 } 43 bool a; 44 a=q.empty(); 45 return a; 46 } 47 else 48 {return true;} 49 } 50 private: 51 stack<int>q; 52 53 };
5、时间复杂度还行,空间复杂度不好!!
原文:https://www.cnblogs.com/hehesunshine/p/11636001.html