LeetCode_234. Palindrome Linked List

强颜欢笑 提交于 2019-12-02 09:53:15

 

234. Palindrome Linked List

Easy

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

Example 1:

Input: 1->2
Output: false

Example 2:

Input: 1->2->2->1
Output: true

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

 

package leetcode.easy;

public class PalindromeLinkedList {
	public boolean isPalindrome(ListNode head) {
		if (head == null) {
			return true;
		}
		java.util.List<Integer> list = new java.util.ArrayList<>();
		while (head != null) {
			list.add(head.val);
			head = head.next;
		}
		int end = list.size() - 1;
		for (int i = 0; i < end; i++, end--) {
			if (!list.get(i).equals(list.get(end))) {
				return false;
			}
		}
		return true;
	}

	@org.junit.Test
	public void test1() {
		ListNode ln1 = new ListNode(1);
		ListNode ln2 = new ListNode(2);
		ln1.next = ln2;
		ln2.next = null;
		System.out.println(isPalindrome(ln1));
	}

	@org.junit.Test
	public void test2() {
		ListNode ln1 = new ListNode(1);
		ListNode ln2 = new ListNode(2);
		ListNode ln3 = new ListNode(2);
		ListNode ln4 = new ListNode(1);
		ln1.next = ln2;
		ln2.next = ln3;
		ln3.next = ln4;
		ln4.next = null;
		System.out.println(isPalindrome(ln1));
	}
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!