首页 > 编程语言 > 详细

Java for LeetCode 234 Palindrome Linked List

时间:2015-11-03 21:17:09      阅读:300      评论:0      收藏:0      [点我收藏+]

解题思路:

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

原文:http://www.cnblogs.com/tonyluis/p/4934272.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!