回文链表
- 偶数情况
- 奇数情况
回文链表leecode
偶数情况
public boolean isPalindrome(ListNode head) {if (head == null) {return true;}ListNode fast = head;ListNode slow = head;while (fast != null && fast.next != null) {fast = fast.next.next;slow = slow.next;}//反转ListNode cur = slow.next;while (cur != null) {ListNode curNext = cur.next;cur.next = slow;slow = cur;cur = curNext;}while (head != slow) {//走之前先判断if (head.val != slow.val) {return false;}//偶数情况if (head.next == slow) {return true;}head = head.next;slow = slow.next;}return true;}
奇数情况
public boolean isPalindrome(ListNode head) {if (head == null) {return true;}ListNode fast = head;ListNode slow = head;while (fast != null && fast.next != null) {fast = fast.next.next;slow = slow.next;}//反转ListNode cur = slow.next;while (cur != null) {ListNode curNext = cur.next;cur.next = slow;slow = cur;cur = curNext;}while (head != slow) {//走之前先判断if (head.val != slow.val) {return false;}//偶数情况if (head.next == slow) {return true;}head = head.next;slow = slow.next;}return true;}