题目描述:
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2 输出: false
示例 2:
输入: 1->2->2->1 输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
解题思路一:先使用快慢指针将链表划分,然后将划分出来的后半段链表逆置,这里使用额外的空间创建新的链表,再将两个链表从尾到头进行比较
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
if(head==null){
return true;
}
int len=0;
ListNode cur=null,tmp=head;
ListNode fast=head,slow=head;
//使用快慢指针将练链表划分成两段
while(fast!=null&&fast.next!=null){
slow=slow.next;
fast=fast.next.next;
}
//将链表后半段逆置
while(slow!=null){
ListNode newNode=new ListNode(slow.val);
if(cur==null){
cur=newNode;
}else{
newNode.next=cur;
cur=newNode;
}
slow=slow.next;
}
//进行比较判断
while(cur!=null){
if(cur.val!=head.val){
return false;
}
cur=cur.next;
head=head.next;
}
return true;
}
}
解题思路二:也是使用快慢指针的方法,只不过直接将链表在原有基础上逆置,空间复杂度为O(1)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
if(head==null||head.next==null){
return true;
}
//注意点,这里fast的赋值
ListNode fast=head.next,slow=head;
while(fast!=null&&fast.next!=null){
slow=slow.next;
fast=fast.next.next;
}
ListNode tmp=slow.next;
ListNode newhead=null;
slow.next=null;
//逆置后半段链表
while(tmp!=null){
ListNode cur=tmp.next;
tmp.next=newhead;
newhead=tmp;
tmp=cur;
}
//将两段链表进行比较
while(newhead!=null){
if(newhead.val!=head.val){
return false;
}
newhead=newhead.next;
head=head.next;
}
return true;
}
}