Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?
判断单链表是否为回文链表
此题用栈来做将非常简单,第一次遍历将节点入栈,第二次遍历判断是否为回文
public class Solution {
public boolean isPalindrome(ListNode head) {
Stack<Integer> s=new Stack<>();
ListNode p=head;
while(p!=null){
s.push(p.val);
p=p.next;
}
while(head!=null){
if(s.pop()!=head.val){
return false;
}
head=head.next;
}
return true;
}
}
但是题目要求O(1)的空间复杂度,显然不能使用栈
可以将链表的后半部分反置,在进行比较
public class Solution {
public boolean isPalindrome(ListNode head) {
ListNode end = head;
ListNode mid = head;
while(end != null && end.next != null){
end = end.next.next;
mid = mid.next;
}
if(end != null)
mid = mid.next;
mid = reverseList(mid);
while(mid != null){
if(mid.val != head.val)
return false;
mid = mid.next;
head = head.next;
}
return true;
}
public ListNode reverseList(ListNode head){
ListNode pre = null;
ListNode cur=head;
ListNode nxt = null;
while(cur != null){
nxt = cur.next;
cur.next = pre;
pre = cur;
cur = nxt;
}
return pre;
}
}