PalindromeLinkedList
- 问题描述:给定一个单向链表,试判断该链表是否是回文链表。
- 解决思路1
- 因为该链表是单向的,所以我们不能想vector那样从后向前访问。
- 所以我们可以先将ListNode存储起来,然后再判断
- 或者是说我们可以利用递归的方法来判断。
- 我们首先用tmp保存head元素。
- 然后利用递归遍历head,访问每一个元素。
- 访问最后一个时候比较该元素和tmp
- 如果相等,则tmp = tmp->next,return true,返回上一个节点
- 如果不想等,则直接return false
- 解决思路2
- 代码
#include <iostream>
#include <vector>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
static ListNode* ListNodeFromVector(vector<int> xs){
ListNode* head = new ListNode(0);
ListNode* first = head;
for(int i=0;i<xs.size();i++){
head->next = new ListNode(xs[i]);
head = head->next;
}
return first->next;
}
void print(){
ListNode* head = this;
while(head){
cout<<head->val<<"->";
head = head->next;
}
cout<<endl;
}
};
class Solution {
public:
ListNode* tmp;
bool isPalindrome(ListNode* head) {
tmp = head;
return check(head);
}
bool check(ListNode* head){
if(head == NULL)
return true;
if(check(head->next) && head->val == tmp->val){
tmp = tmp->next;
return true;
}
return false;
}
bool isPalindromeV2(ListNode* head){
if(head == NULL)
return true;
ListNode* dump = new ListNode(0);
dump->next = head;
ListNode* slow = dump;
ListNode* fast = dump;
while(slow->next && fast->next){
fast = fast->next;
if(fast->next){
fast = fast->next;
slow = slow->next;
}
}
ListNode* last2 = NULL;
ListNode* start2 = slow->next;
while(last2 != fast){
ListNode* tmp = start2->next;
start2->next = last2;
last2 = start2;
start2 = tmp;
}
slow->next = NULL;
slow = head;
while(slow && fast){
if(slow->val == fast->val)
{
slow = slow->next;
fast = fast->next;
continue;
}else{
return false;
}
}
return true;
}
static void solution(){
ListNode* head = ListNode::ListNodeFromVector({});
Solution solution1;
cout<<solution1.isPalindromeV2(head)<<endl;
}
};