Given a singly linked list, determine if it is a palindrome.
Example 1:
Input: 1->2
Output: false
Example 2:
Input: 1->2->2->1
Output: true
Time: O(N) Space: O(N)
/**
* 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;
Stack<Integer> stack = new Stack<Integer>();
ListNode node = head;
while(node!=null){
stack.push(node.val);
node = node.next;
}
node = head;
while(stack.size()!= 0 && stack.peek() == node.val){
stack.pop();
node = node.next;
}
return stack.size() == 0 && node == null;
}
}
Follow up:
Could you do it in O(n) time and O(1) space?
思路:用双指针,找到中点,然后翻转后面的linkedlist,然后两段linkedlist分别走,如果不相等则返回false。
值得一提的是:长度的奇偶情况,reverse之后,并不需要完全一样,因为有一个长度比较长,只要前面的走完一致就可以了,最后一个点不需要相同,可以相同也可以一个为null,一个为数;
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
if(head == null || head.next == null) {
return true;
}
ListNode dummpy = new ListNode(-1);
dummpy.next = head;
ListNode slow = dummpy;
ListNode fast = dummpy;
while(fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
ListNode newhead = slow.next;
ListNode nhead = reverseLinkedList(newhead);
return compareTwoList(head, nhead);
}
//最重要的是,奇数和偶数的情况,并不需要最后一致走完,也就是奇数的情况,1 2 1, reverse完之后,比较1就可以了
private boolean compareTwoList(ListNode n1, ListNode n2) {
while(n1 != null && n2 != null) {
if(n1.val != n2.val) {
return false;
}
n1 = n1.next;
n2 = n2.next;
}
return true; // 这里直接return true很关键;
}
private ListNode reverseLinkedList(ListNode head) {
ListNode dummpy = new ListNode(-1);
dummpy.next = head;
ListNode cur = head;
while(cur != null && cur.next != null) {
ListNode curnext = cur.next;
cur.next = curnext.next;
curnext.next = dummpy.next;
dummpy.next = curnext;
}
return dummpy.next;
}
}