leetcode 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

 
这个题是根叔想出来了- - 
刚开始我想的是所有的值存到vector里,然后memory limit exceeded了。
 
后来想怎么都没办法不存啊。
根叔说,把后半部分反转。然后两个链表在从头开始比较。
链表反转刚开始我也不会(PS.我最近智商怎么这么低啊)
 
链表反转,就拿出一个节点然后把它插到头部就可以了。
 
写完了程序,然后一直runtime error~一直找不到原因,后来发现假如你要用到某个指针,就一定要初始化,初始化为NULL啊~
 
 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  
10  //反转后半部分链表,然后和前部分链表进行比对
11 class Solution {
12 public:
13     ListNode* reverse(ListNode *head,int len){    //重新插入逆序
14         ListNode* p=NULL,*q=NULL;
15         while(len>0){
16             q=head->next;
17             head->next=p;
18             p=head;
19             head=q;
20             len--;
21         }
22         return p;
23     }
24     
25     
26     bool isPalindrome(ListNode* head) {
27         if(head==NULL) return true;
28         int len=0,c=0;
29         ListNode *p=head,*head1=head;
30         while(p!=NULL) {p=p->next;len++;}
31         if(len%2==0) c=len/2;
32         else c=len/2+1;
33         while(c>0) {head1=head1->next;c--;}
34         head1=reverse(head1,len/2);
35         c=len/2;
36         while(c>0){
37             c--;
38             if(head->val==head1->val) {
39                 head=head->next;
40                 head1=head1->next;
41                 }
42             else return false;}
43             return true;
44     }
45 };
原文地址:https://www.cnblogs.com/LUO77/p/5067208.html