請判斷一個鏈表是否為回文鏈表。
示例 1:
輸入: 1->2
輸出: false
示例 2:
輸入: 1->2->2->1
輸出: true
進階:
你能否用?O(n) 時間復雜度和 O(1) 空間復雜度解決此題?
思路:逆置前一半,然后從中心出發開始比較即可。
/*** 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 slow = head, fast = head;ListNode pre = head, prepre = null;while(fast != null && fast.next != null) {pre = slow;slow = slow.next;fast = fast.next.next;pre.next = prepre;prepre = pre;}if(fast != null) {slow = slow.next;}while(pre != null && slow != null) {if(pre.val != slow.val) {return false;}pre = pre.next;slow = slow.next;}return true;}
}
?