请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
解法1:栈
public boolean isPalindrome(ListNode head) {
if (head==null)
return true;
ListNode a=head;
Stack stack=new Stack();
while (a!=null){
stack.push(a);
a=a.next;
}
while (head!=null){
ListNode node= (ListNode) stack.pop();
if (node.val!=head.val){
return false;
}else {
head=head.next;
}
}
return true;
}
解法2:快慢指针
public boolean isPalindrome(ListNode head) {
if (head==null || head.next==null)
return true;
ListNode fast=head;
ListNode slow=head;
while (fast.next!=null&&fast.next.next!=null){
fast=fast.next.next;
slow=slow.next;
}
ListNode lastHalf=reverseListNode(slow.next);
while (lastHalf!=null){
if (head.val!=lastHalf.val){
return false;
}
head=head.next;
lastHalf=lastHalf.next;
}
return true;
}
public ListNode reverseListNode(ListNode slow){
ListNode head=slow;
ListNode a=null;
while (slow!=null){
ListNode b=slow.next;
head.next=a;
a=head;
head=b;
slow=b;
}
return a;
}