#链表# 234. 回文链表 leetcode-cn.com/problems/pa…
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2 输出: false 示例 2:
输入: 1->2->2->1 输出: true
方法1
public class _234_回文链表 {
public static void main(String[] args) {
ListNode node1 = new ListNode(-129);
ListNode node2 = new ListNode(-129);
node1.next = node2;
boolean istrue = isPalindrome(node1);
}
public static boolean isPalindrome(ListNode head) {
List list = new ArrayList();
while (head != null){
list.add(head.val);
head = head.next;
}
int firstIndex = 0;
int last = list.size() -1;
while(firstIndex < last){
if (!list.get(firstIndex).equals(list.get(last))) {
return false;
}
firstIndex ++;
last --;
}
return true;
}
}
方法2 利用快慢指针,把链表分成两部分,把后半部分反转,最后在反转回来
public static boolean isPalindrome(ListNode head) {
if (head == null)return true;
//找到链表中间,
ListNode firstHalfEnd = endOfFirstHalf(head);
//反转后半部分
ListNode secondHalfStart = reverseList(firstHalfEnd.next);
ListNode p1 = head;
ListNode p2 = secondHalfStart;
boolean result = true;
while (result && p2 != null) {
if (p1.val != p2.val) result = false;
p1 = p1.next;
p2 = p2.next;
}
// Restore the list and return the result.
firstHalfEnd.next = reverseList(secondHalfStart);
return result;
}
//找到listNode 的中点
private static ListNode endOfFirstHalf(ListNode head){
ListNode slowNode = head;
ListNode fastNode = head.next;
while (fastNode.next != null && fastNode.next.next != null){
slowNode = slowNode.next;
fastNode = fastNode.next.next;
}
return slowNode;
}
//反转列表
private static ListNode reverseList(ListNode head){
ListNode prev = null;
ListNode curr = head;
while (curr != head){
ListNode temp = curr.next;
curr.next = prev;
prev = curr;
curr = temp;
}
return prev;
}
回文问题: [1,0,1] 也算回文