Leetcode Palindrome Linked List 这个题目相对简单,回文串的相关题目我们也见过很多,本题要求在o(n)的时间,与o(1)的空间完成,在链表中还是有一定的思考价值的,相关代码如下,并给出测试:
#include<iostream>
using namespace std;
//Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
// First count the num of the node
// Reverse the pre num / 2 node
// Compare the node val for the centre to the edge
// the time complex is O(n), and the space complex O(1)
class Solution {
public:
bool isPalindrome(ListNode* head) {
int count = 0;
int reverse_count = 0;
ListNode* cur = head;
ListNode* pre;
ListNode* next;
ListNode* cur_re;
// Count the number of the node
while (cur != NULL) {
cur = cur->next;
count ++;
}
reverse_count = count / 2;
cur = head;
pre = NULL;
// Reverse the first count / 2 node
while (reverse_count != 0) {
next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
reverse_count --;
}
cur_re = pre;
cur = count % 2 == 0? cur: cur->next;
// Compare the node val from the center to the edge
while (cur != NULL) {
if (cur->val != cur_re->val) {
return false;
}
cur = cur->next;
cur_re = cur_re->next;
}
return true;
}
};
int main(int argc, char* argv[]) {
ListNode* l = new ListNode(0);
ListNode* cur = l;
cur->next = new ListNode(1);
cur = cur->next;
cur->next = new ListNode(1);
cur = cur->next;
cur->next = new ListNode(0);
cur = cur->next;
Solution so;
bool re = so.isPalindrome(l);
cout<<"result: "<<re<<endl;
}