请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
快慢指针
/**
* 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) {
ListNode* slow = head, * fast = head;
while(fast != NULL && fast->next != NULL){
slow = slow->next;
fast = fast->next->next;
}
if(fast != NULL){
slow = slow->next;
}
slow = reverse(slow);
fast = head;
while(slow != NULL){
if(slow->val != fast->val){
return false;
}
slow = slow->next;
fast = fast->next;
}
return true;
}
ListNode* reverse(ListNode* head){
if(head == NULL){
return NULL;
}
ListNode * pre, *cur, *nex;
pre = NULL;
cur = head;
nex = head;
while(cur != NULL){
nex = cur->next;
cur->next = pre;
pre = cur;
cur = nex;
}
return pre;
}
};
栈
/**
* 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) return false;
ListNode* cur = head;
stack<int> stk;
int length = 0;
while(cur != NULL){
stk.push(cur->val);
cur = cur->next;
length++;
}
int index = 0;
while(head != NULL && index < length /2){
if(head->val != stk.top()){
return false;
}
head = head->next;
stk.pop();
index++;
}
return true;
}
};