一、题目内容

image.png

二、题解

解法1:

思路

反转后半部分
fast!=null时,说明是奇数长度

代码

  1. public class Solution {
  2. /**
  3. *
  4. * @param head ListNode类 the head
  5. * @return bool布尔型
  6. */
  7. public boolean isPail (ListNode head) {
  8. // write code here
  9. ListNode fast = head, slow = head;
  10. //通过快慢指针找到中点
  11. while (fast != null && fast.next != null) {
  12. fast = fast.next.next;
  13. slow = slow.next;
  14. }
  15. if(fast!=null){
  16. slow = slow.next;
  17. }
  18. slow = reverse(slow);
  19. fast = head;
  20. while(slow !=null){
  21. if(fast.val!=slow.val){
  22. return false;
  23. }
  24. fast = fast.next;
  25. slow = slow.next;
  26. }
  27. return true;
  28. }
  29. private ListNode reverse(ListNode head){
  30. ListNode pre = null;
  31. ListNode cur = head;
  32. while(cur!=null){
  33. ListNode next = cur.next;
  34. cur.next = pre;
  35. pre = cur;
  36. cur = next;
  37. }
  38. return pre;
  39. }
  40. }

解法2:

思路

队列

代码

  1. public class Solution {
  2. /**
  3. *
  4. * @param head ListNode类 the head
  5. * @return bool布尔型
  6. */
  7. public boolean isPail (ListNode head) {
  8. // write code here
  9. Deque<Integer> deque = new LinkedList<Integer>();
  10. while(head!=null){
  11. deque.offer(head.val);
  12. head = head.next;
  13. }
  14. while(deque.size()>=2){
  15. if(!deque.removeFirst().equals(deque.removeLast())){
  16. return false;
  17. }
  18. }
  19. return deque.isEmpty() || deque.size() == 1;
  20. }
  21. }