//不可慢指针先走在这种快慢指针里边走边找中点,不然慢指针在反转的时候会影响到快指针正常的路径。 public static boolean isPalindrome2_defeat(ListNode head) { if(head.next==null) return true; ListNode s = new ListNode(-1, head); //先考虑两个及以上的节点情况: ListNode slow = s; ListNode fast = s; ListNode n1 = s; int flag = 0; while (fast.next != null) { slow = slow.next; s.next = slow.next; slow.next = s;//注意已经将节点给移除了,所以不可这样判断 n1=slow; slow = s; //fast = fast.next; if (fast.next == null) { flag = 1;//说明121; break; } else fast = fast.next; } if(flag==1){ while (n1!=s){ if(n1.next.val!=slow.next.val){ break; } else n1=n1.next; slow=slow.next; } if(n1==s) return true; else return false; } else { while (n1!=s){ if(n1.val!=slow.next.val){ break; } else n1=n1.next; slow=slow.next; } if(n1==s) return true; else return false; } } public static ListNode reverseList(ListNode head) { if (head.next == null || head == null) return head; ListNode last = reverseList(head.next); head.next.next = head; head.next = null; return last; } public static void main(String[] args) { ListNode head = new ListNode(1, null); ListNode head1 = new ListNode(1, new ListNode(2,new ListNode(2,new ListNode(1,null)))); System.out.println(isPalindrome2_defeat(head1)); }
leetCode-isPalindrome2_defeat
于 2023-07-10 23:35:16 首次发布