problems:
Given a singly linked list, determine if it is a palindrome.
Example 1:
Input: 1->2
Output: false
Example 2:
Input: 1->2->2->1
Output: true
tip:
判断某链表是否是回文。
solutions:
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> list_node;
while(head)
{
list_node.push_back(head->val);
head=head->next;
}
int n = list_node.size();
for(int i=0,j=n-1;i<n&&i<=j;i++,j--)
{
if(list_node[i] != list_node[j])
return false;
}
return true;
}
};
2.利用栈先进后出的性质。
class Solution {
public:
bool isPalindrome(ListNode* head) {
stack<int> list_node;
ListNode* cur=head;
while(cur)
{
list_node.push(cur->val);
cur=cur->next;
}
while(head)
{
int stack_head=list_node.top();
list_node.pop();
if(head->val != stack_head)
return false;
head=head->next;
}
return true;
}
};
3.快慢指针的应用。慢指针走一步,快指针走两步,当快指针到达链表尾部时,慢指针到达中间位置。将链表后半段位置反转,然后比较。
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(!head || !head->next) return true;
ListNode* slow=head;
ListNode* fast=head;
while(fast->next && fast->next->next)
{
slow = slow->next;
fast = fast->next->next;
}
ListNode* last = slow->next;
while(last->next)//链表位置反转
{
ListNode* tmp = last->next;
last->next = tmp->next;
tmp->next = slow->next;
slow->next = tmp;
}
while(slow->next)
{
slow = slow->next;
if(head->val != slow->val)
return false;
head = head->next;
}
return true;
}
};