/**
* @author johnsondu
* @problem Palindrome Linked List
* @url https://leetcode.com/problems/palindrome-linked-list/
* @timeComlexity O(n)
* @spaceComplexity O(n)
* @strategy Using a stack to store the value in linkList
*/
/**
* 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 || head->next == NULL) return true;
ListNode *p = head;
stack<int> st;
while(p) {
st.push(p->val);
p = p->next;
}
while(head) {
int val = st.top();
st.pop();
if(val != head->val) return false;
head = head->next;
}
return true;
}
};
上述采用一个栈来存储值,时间复杂度和空间复杂度都为O(n).
接下来,我们用dfs来进行时间复杂度O(n), 空间复杂度O(1) 的方法。 总体思想是先存储一个全局头结点,遍历到最后一个元素时,进行比较,同时把头结点往后移一位。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
ListNode *p;
public:
void dfs(ListNode* head, bool &flag) {
if(head == NULL) return;
dfs(head->next, flag);
if(p->val != head->val) flag = false;
else p = p->next;
}
bool isPalindrome(ListNode* head) {
if(head == NULL || head->next == NULL) return true;
p = head;
bool flag = true;
dfs(head, flag);
return flag;
}
};