Problem:
Given a singly linked list, determine if it is a palindrome.
Example 1:
Input: 1->2 Output: falseExample 2:
Input: 1->2->2->1 Output: trueFollow up:
Could you do it in O(n) time and O(1) space?
Analysis:
本题的思路就是首先将原来的链表进行逆转,然后将其和原来的链表进行匹配,如果出现不相等,则直接返回false。代码如下:
Code:
/**
* 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;
ListNode reverseLists = new ListNode(-1);
ListNode p = head, cur = reverseLists;
while(p != null) {
ListNode temp = new ListNode(p.val);
ListNode nxt = reverseLists.next;
reverseLists.next = temp;
temp.next = nxt;
p = p.next;
}
p = head;
cur = cur.next;
while(p != null) {
if(cur.val != p.val)
return false;
cur = cur.next;
p = p.next;
}
return true;
}
}