1. 程式人生 > >234. Palindrome Linked List【Easy】【判斷鏈表是否回文】

234. Palindrome Linked List【Easy】【判斷鏈表是否回文】

put false ali lean pre lis inf pan span

Given a singly linked list, determine if it is a palindrome.

Example 1:

Input: 1->2
Output: false

Example 2:

Input: 1->2->2->1
Output: true

Follow up:
Could you do it in O(n) time and O(1) space?

/**
 * 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; ListNode fast = head; while(fast != null && fast.next != null) { slow = slow.next; fast
= fast.next.next; } if(fast != null) slow = slow.next; //slow是中點,將中點反轉後 slow = reverse(slow); fast = head; while(slow != null) { if(slow.val != fast.val) return false; slow = slow.next; fast
= fast.next; } return true; } public ListNode reverse(ListNode head) { ListNode pre = null; ListNode next = null; while(head != null) { next = head.next; head.next = pre; pre = head; head = next; } return pre; } }

技術分享圖片

234. Palindrome Linked List【Easy】【判斷鏈表是否回文】