【30】234. Palindrome Linked List
234. Palindrome Linked List
Total Accepted: 86231
- Total Submissions: 271389
- Difficulty: Easy
- Contributors: Admin
Given a singly linked list, determine if it is a palindrome.
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 //用到stack存前半部的节点值 12 bool isPalindrome(ListNode* head) { 13 if(!head || !head -> next) return true; 14 ListNode* slow = head, *fast = head; 15 stack<int> s; 16 s.push(head -> val);//别忘了要存进head的值 17 while(fast -> next && fast -> next ->next){ 18 slow = slow -> next; 19 fast = fast -> next -> next; 20 s.push(slow -> val); 21 } 22 if(!fast -> next){ 23 s.pop();//如果链表是奇数个的话,只记到中点之前的值。因为每次比较,我们要从slow的后一个开始比。 24 } 25 while(slow -> next){ 26 slow = slow -> next; 27 int tmp = s.top(); 28 s.pop(); 29 if(tmp != slow -> val){ 30 return false; 31 } 32 } 33 return true; 34 } 35 };
Follow up:
Could you do it in O(n) time and O(1) space?
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 if(!head || !head->next) return true; 13 ListNode* slow = head, *fast = head; 14 while(fast -> next && fast -> next -> next){ 15 slow = slow -> next; 16 fast = fast -> next -> next; 17 } 18 ListNode* pre = head; 19 ListNode* last = slow -> next; 20 //因为follow up要求space是1 所以翻转后半部分 再从slow的next开始与pre的值进行比较 21 while(last -> next){ 22 ListNode* tmp = last -> next; 23 last -> next = tmp -> next; 24 tmp -> next = slow -> next; 25 slow -> next = tmp;//slow一直不变,其余节点不停往其后插入 26 } 27 while(slow -> next){ 28 slow = slow -> next;//从slow的next开始比较, 这时即可忽略当前的slow节点。反正是单个节点,可不比较;或者总数是偶数,即可一直比较。 29 if(pre -> val != slow -> val) return false; 30 pre = pre -> next;//别忘了pre也要往前走 31 } 32 return true; 33 } 34 };