Java for LeetCode 234 Palindrome Linked List

解题思路:

O(1)的空间复杂度,意味着不能通过开一个List来解决问题。我们可以把List分成前后两个部分,后半部分通过指针的相互赋值进行翻转即可。

JAVA实现如下:

public static boolean isPalindrome(ListNode head) {
		if (head == null || head.next == null)
			return true;
		ListNode middle = head, fast = head;
		while (fast != null && fast.next != null) {
			middle = middle.next;
			fast = fast.next.next;
		}
		ListNode rightHalf = reverseListNode(middle);
		while (rightHalf != null) {
			if (rightHalf.val != head.val)
				return false;
			head = head.next;
			rightHalf = rightHalf.next;
		}
		return true;
	}

	public static ListNode reverseListNode(ListNode head) {
		if (head == null || head.next == null)
			return head;
		ListNode pre = head, cur = head.next, tmp = head;
		head.next = null;
		while (cur != null) {
			tmp = cur.next;
			cur.next = pre;
			pre = cur;
			cur = tmp;
		}
		return pre;
	}

 

你可能感兴趣的:(Java for LeetCode 234 Palindrome Linked List)