Leetcode:(234) Palindrome Linked List(java)
阿新 • • 發佈:2018-11-06
package LeetCode_LinkedList; /** * 題目: * 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? * 解題思路: * 找到連結串列中間節點,將連結串列分成兩段,然後將後段連結串列進行反轉, * 最後將反轉後的連結串列依次與前半段連結串列進行比較,確定是否相等。 */ public class IsPalindrome_234_1016 { public boolean IsPalindrome(ListNode head) { if (head == null || head.next == null) { return true; } ListNode fast = head; ListNode slow = head; //將連結串列分成前後兩部分 while (fast != null && fast.next != null) { fast = fast.next.next; slow = slow.next; } if (fast != null) { slow = slow.next; } //反轉連結串列 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 node = head; while (node != null) { ListNode next = node.next; node.next = pre; pre = node; node = next; } return pre; } public static void main(String[] args) { ListNode node1 = new ListNode(1); ListNode node2 = new ListNode(2); //ListNode node3 = new ListNode(2); //ListNode node4 = new ListNode(1); node1.next = node2; //node2.next = node3; //node3.next = node4; IsPalindrome_234_1016 test = new IsPalindrome_234_1016(); boolean result = test.IsPalindrome(node1); System.out.println(result); } }