- Palindrome Linked List
Implement a function to check if a linked list is a palindrome.
Example
Example 1:
Input: 1->2->1
output: true
Example 2:
Input: 2->2->1
output: false
Challenge
Could you do it in O(n) time and O(1) space?
解法1:
我用的stack。
注意:
1)奇数和偶数,midIndex都是len/2 - 1。
但奇数的midIndex要从midIndex后面2个开始。
2) 求链表的中点也可以用快慢指针法。
代码如下:
/**
* Definition of singly-linked-list:
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: A ListNode.
* @return: A boolean.
*/
bool isPalindrome(ListNode * head) {
if (!head || !head->next) return true;
int len = 0;
ListNode * p = head;
while(p) {
len++;
p = p->next;
}
//1->2->1, midIndex = 0;
//1->2->2->1, midIndex = 1;
int midIndex = len / 2 - 1;
stack<int> s;
p = head;
for (int i = 0; i <= midIndex; ++i) {
s.push(p->val);
p = p->next;
}
if (len & 0x1) p = p->next; //1->2->1, p points to the 2nd 1
while(p) {
if (p->val == s.top()) {
p = p->next;
s.pop();
} else {
return false;
}
}
return true;
}
};
解法2:
空间O(1)的算法就是把后半段链表反转后看是不是和前半段链表相等。TBD。
代码同步在
https://github.com/luqian2017/Algorithm
来源:CSDN
作者:纸上得来终觉浅 绝知此事要躬行
链接:https://blog.csdn.net/roufoo/article/details/104169186