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?
給定一個(gè)單鏈表,判斷是否是回文鏈表
算法分析
首先產(chǎn)生該鏈表的逆序鏈表,然后比較兩個(gè)鏈表的前半部分即可。
Java代碼
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isPalindrome(ListNode head) {
//創(chuàng)建一個(gè)逆序的鏈表
ListNode node = head;
ListNode tail = null;
int counter = 0;
while (node != null) {
ListNode temp = new ListNode(node.val);
temp.next = tail;
tail = temp;
node = node.next;
counter++;
}
counter /= 2;
//比對(duì)原鏈表與逆序鏈表是否一致
while (counter != 0) {
counter--;
if (tail.val != head.val) {
return false;
}
head = head.next;
tail = tail.next;
}
return true;
}
}