• LeetCode_234. Palindrome Linked List


    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;
    
    /**
     * Definition for singly-linked list. public class ListNode { int val; ListNode
     * next; ListNode(int x) { val = x; } }
     */
    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));
    	}
    }
    
  • 相关阅读:
    学习进度条 第十五周
    学习进度条 第十四周
    买书问题
    第二冲刺阶段 工作总结 10
    第二冲刺阶段 工作总结09
    05构建之法阅读笔记之五
    第二阶段工作总结 08
    React 浅析
    React 开发规范
    React 组件的生命周期
  • 原文地址:https://www.cnblogs.com/denggelin/p/11741644.html
Copyright © 2020-2023  润新知