234. Palindrome Linked List
一、题目
1、审题
2、判断链表中的节点结构是否是回文形式。
二、解答
1、思路
①、采用两个指针 fast、slow向后移动,最终 slow 移动到了中间的位置(可能右边节点数多 1 个)
②、将 slow 右边的所有节点进行翻转,最终 slow 指向右端的起始节点,fast 指向 head
③、slow 与 fast 节点依次比较,若不相等,则返回false,若最终 slow == null,返回 true
1 public boolean isPalindrome(ListNode head) { 2 3 if(head == null || head.next == null) 4 return true; 5 6 ListNode fast = head, slow = head; 7 while(fast != null && fast.next != null) { 8 fast = fast.next.next; 9 slow = slow.next; 10 } 11 if(fast != null) // odd nodes: let right half smaller 12 slow = slow.next; 13 14 slow = reverseList(slow); 15 fast = head; 16 17 while(slow != null) { 18 if(fast.val != slow.val) 19 return false; 20 slow = slow.next; 21 fast = fast.next; 22 } 23 return true; 24 } 25 26 private ListNode reverseList(ListNode head) { 27 ListNode prev = null; 28 while(head != null) { 29 ListNode next = head.next; 30 head.next = prev; 31 prev = head; 32 head = next; 33 } 34 return prev; 35 }