Lettcode_234_Palindrome Linked List

本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/47334465


Given a singly linked list, determine if it is a palindrome.

Follow up:
Could you do it in O(n) time and O(1) space?


思路:

(1)题意为给定一个链表,判断该链表是否“回文”,即该链表中每个节点的值组成的串是否为回文串。

(2)下面对该题解法的时间复杂度为O(n),思路为:首先,申请两个StringBuffer用来保存数据;其次,遍历链表一次,将链表中每个节点的值加到StringBuffer中,在此过程中将链表逆序;最后,再次遍历逆序后的链表,将链表中每个节点的值追加到另一个StringBuffer中,然后比较两个StringBuffer是否完全相同,如果相同则回文,否则不是回文。

(3)详情见下方代码。希望本文对你有所帮助。


算法代码实现如下:

package leetcode;

import leetcode.utils.ListNode;

/**
 * @author lqq
 */
public class Palindrome_LinkedList {

	/* Could you do it in O(n) time and O(1) space? */

	public static boolean isPalindrome(ListNode head) {

		// 思路为将链表翻转,判断新旧链表是否对应位置元素相等
		if (head == null || (head!=null&&head.next==null))
			return true;
		
		ListNode fis = head;
		ListNode sed = head.next;
		fis.next = null;
		StringBuffer buffer = new StringBuffer();
		buffer.append(fis.val);
		while (sed != null) {
			buffer.append(sed.val);
			ListNode thd = sed.next;
			sed.next = fis;
			fis = sed;
			sed = thd;
		}

		StringBuffer buffer2 = new StringBuffer();

		while(fis!=null){
			buffer2.append(fis.val);
			fis = fis.next;
		}

		return buffer2.toString().equals(buffer.toString());
	}
}

你可能感兴趣的:(java,LeetCode,算法)