1. 程式人生 > >LeetCode:234. Palindrome Linked List(判斷一個連結串列是不是迴文連結串列)

LeetCode:234. Palindrome Linked List(判斷一個連結串列是不是迴文連結串列)

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?


方法1:(常規方法)

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isPalindrome(ListNode head) {
        List<Integer> list = new ArrayList<>();
        while(head! = null){
            list.add(head.val);
            head = head.next;
        }
        return isPalindromeList(list);
    }
    public boolean isPalindromeList(List<Integer> list){
        int i = 0;
        int j = list.size()-1;
        while(i < j){
            if(list.get(i) != list.get(j)){
                return false;
            }
        }
        return true;
    }
}

時間複雜度:O(n)

空間複雜度:O(n)