回文链表
问题描述:
请判断一个链表是否为回文链表
解法一:
得到所有的值,转换为判断会问数组
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
ptr=head
val=[]
if (not head) or head.next==None:
return True
while(ptr):
val.append(ptr.val)
ptr=ptr.next
a=len(val)
if (a==2):
if val[0]==val[1]:
return True
else:
return False
print(val[0:a//2])
b=val[ceil(a/2):a]
print()
if(val[0:a//2]==b[::-1]):
return True
else:
return False
这是把后半数组反转判断,可以省一点时间,也可以直接对全部数组反转:
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
ptr=head
val=[]
if (not head) or head.next==None:
return True
while(ptr):
val.append(ptr.val)
ptr=ptr.next
if(val==val[::-1]):
return True
else:
return False
开辟了数组,空间复杂度o(n),时间复杂度o(n)。
解法二:快慢指针
利用快慢指针把练链表分为前半部分和后半部分,快慢指针的移动参考下图
并且在慢指针移动的过程中进行前面链表的反转,可以节省时间。
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
fast=slow=head
pre=slow
prepre=None
while(fast!=None and fast.next!=None):
fast=fast.next.next
pre=slow
slow=slow.next
pre.next=prepre
prepre=pre
if fast!=None:
slow=slow.next
while(slow!=None and prepre!=None):
if slow.val!=prepre.val:
return False
slow=slow.next
prepre=prepre.next
else:
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)
return true;
if (head->next == NULL)
return true;
// 使用快慢指针把链表拆分成前后两部分,同时将链表前半部分反转。
// slow 指向中间节点或下中位节点。
ListNode *fast = head;
ListNode *slow = head;
ListNode *prepre = NULL;
ListNode *pre = slow;
while(fast!=NULL && fast->next!=NULL){
fast=fast->next->next;
pre=slow;
slow=slow->next;
pre->next=prepre;
prepre=pre;
}
if(fast!=NULL){
slow=slow->next;
}
while(slow!=NULL || prepre!=NULL){
if (slow->val!=prepre->val){
return false;
}
slow=slow->next;
prepre=prepre->next;
}
return true;
}
};
解法三:栈
利用栈先入后出的特性,可以判断回文。
class Solution {
public:
bool isPalindrome(ListNode* head) {
stack<int> s;
ListNode *p = head;
while(p){
s.push(p->val);
p = p->next;
}
p = head;
while(p){
if(p->val != s.top()){
return 0;
}
s.pop();
p = p->next;
}
return 1;
}
};