請判斷一個鏈表是否為回文鏈表。
示例 1:
輸入: 1->2
輸出: false
示例 2:
輸入: 1->2->2->1
輸出: true
代碼
/*** 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 fast=head,slow=head,pre=null;while (fast!=null&&fast.next!=null){pre=slow;slow=slow.next;fast=fast.next.next;}//快慢指針找出中點pre.next=null;//從中點切斷鏈表pre=null;while (slow!=null)//倒置后部分鏈表{ListNode temp=slow.next;slow.next=pre;pre=slow;slow=temp;}while (pre!=null&&head!=null)//將兩個鏈表比較{if(pre.val!=head.val) return false;pre=pre.next;head=head.next;}return true;}
}