我们可以采用双指针的办法进行,如下图:
如果链表长度为偶数,则直接从第二个指针的位置开始对链表进行反转;如果是奇数,则从第二指针的下一位进行链表反转
代码实现:
public static void main(String[] args) {ListNode next4 = new ListNode(1, null);ListNode next3 = new ListNode(2, null);ListNode next2 = new ListNode(2, next3);ListNode next1 = new ListNode(1, next2);System.out.println("是否是回文链表:" + isPalindrome(next1));}//回文链表private static boolean isPalindrome(ListNode node) {ListNode fast = node, slow = node;while (fast != null && fast.node != null) {fast = fast.node.node;slow = slow.node;}if (fast != null) {slow = slow.node;}slow = reverse(slow);while (slow != null) {if (slow.val != node.val) {return false;}slow = slow.node;node = node.node;}return true;}private static ListNode reverse(ListNode slow) {if (slow.node == null) {return slow;}ListNode temp = null,next;while (slow != null) {next = slow.node;slow.node = temp;temp = slow;slow = next;}return slow;}