题目描述:

LeetCode_234. Palindrome Linked List_链表


思路1:申请一个vector,把链表中的元素都复制到vector中,然后用双指针从两端向中间比较

/**
* 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) {
vector<int> copy;
ListNode* p=head;
while(p){
copy.push_back(p->val);
p=p->next;
}
int n=copy.size();
int i=0,j=n-1;
while(i<j){
if(copy[i]==copy[j]){
i++;
j--;
}else{
return false;
}
}
return true;
}
};
/**
* 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;
return ISPAL(head);
}
bool ISPAL(ListNode* head){
ListNode* fast,*slow;
fast=slow=head;
//这种循环方式保证了slow是中间的节点或者是中间的前一个节点
while(fast->next&&fast->next->next){
slow=slow->next;
fast=fast->next->next;
}
slow->next=reverse(slow->next);
slow=slow->next;
while(slow){
if(head->val!=slow->val)
return false;
head=head->next;
slow=slow->next;
}
return true;
}
ListNode* reverse(ListNode* &head){
ListNode* pre=head;
ListNode* cur=pre->next;
ListNode* p;
while(cur){
if(pre==head)
pre->next=NULL;
p=cur->next;
cur->next=pre;
pre=cur;
cur=p;
}
return pre;
}
};