Leetcode 234. Palindrome Linked List

来源:互联网 发布:矩阵分析中文版 pdf 编辑:程序博客网 时间:2024/06/16 16:29

O(n) time and O(1) space, reverse left half of the list.

public class Solution {    public boolean isPalindrome(ListNode head) {        ListNode slow = head;        ListNode fast = head;                while (fast != null && fast.next != null) {            slow = slow.next;            fast = fast.next.next;        }        // Start from slow, reverse the list        ListNode newHead = helper(slow, null);                // while (slow != null) {        //     ListNode next = slow.next;        //     slow.next = newHead;        //     newHead = slow;        //     slow = next;        // }                        // No matter the length of the list is odd or even, it will stop the loop when any of the two heads is null        while (head != null && newHead != null) {            if (head.val != newHead.val)                return false;            head = head.next;            newHead = newHead.next;        }                return true;    }        // Recursive approach to reverse a list    public ListNode helper(ListNode head, ListNode newHead) {        if (head == null)            return newHead;        ListNode next = head.next;        head.next = newHead;        return helper(next, head);    }}

O(n) time and space.

public class Solution {    public boolean isPalindrome(ListNode head) {        // Save all values in the list to an arraylist        ListNode temp = head;        List<Integer> values = new ArrayList<Integer>();        while (temp != null) {            values.add(temp.val);            temp = temp.next;        }                int left = 0, right = values.size()-1;        while (left < right) {            if (!values.get(left).equals(values.get(right)))                return false;            left++;            right--;        }                return true;    }}

public class Solution {    public boolean isPalindrome(ListNode head) {        // need a stack to save half of the list        Stack<Integer> stack = new Stack<>();                // count the number of nodes        int cnt = 0;        ListNode tmp = head;        while (tmp != null) {            tmp = tmp.next;            cnt++;        }        boolean isOdd = (cnt % 2 == 1);                // push the first half and compare the second half with elements in stack        int half = 0;        while (head != null) {            if (half < cnt/2) {                stack.push(head.val);                half++;            }            else if (isOdd) {                isOdd = false;            }            else {                if (stack.pop() != head.val)                     return false;            }            head = head.next;        }                return true;    }}


0 0
原创粉丝点击