LeetCode 234 Palindrome Linked List(回文链表)(*)

来源:互联网 发布:淘宝版本低无法登陆 编辑:程序博客网 时间:2024/06/12 11:04

翻译

给定一个单链表,判断它是否是回文的。

跟进:
你可以只用O(n)的时间和O(1)的空间吗?

原文

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?

分析

一种比较简单的做法,用stack来存储值,充分利用了栈的后进先出的特点进行对值的反转。

public class Solution {    public boolean isPalindrome(ListNode head) {        Stack<Integer> original = new Stack<>();        int len = 0;        while (head != null) {            original.push(head.val);            head = head.next;            len++;        }        Stack<Integer> compare = new Stack<>();        for (int i = 0; i < len / 2; i++) {            compare.push(original.pop());        }        if (len % 2 != 0)            original.pop();        while (!original.empty()) {            int a = original.pop();            int b = compare.pop();            if (original.pop() != compare.pop())                return false;        }        return true;    }}

除此之外,也可以直接对链表进行反转。

比如说对于 1 -> 2 -> 3 -> 4 -> 3 -> 2 -> 1,反转后半部分,得到 1 -> 2 -> 3 -> 4 -> 1 -> 2 -> 3,然后直接逐个遍历比较即可。下面的代码中我已经附上了注释,就不多说了。

代码

Java

public class Solution {    public ListNode reverse(ListNode head) {        ListNode newHead = null;        while (head != null) {            ListNode tmp = head.next;            head.next = newHead;            newHead = head;            head = tmp;        }        return newHead;    }    public boolean isPalindrome(ListNode head) {        if (head == null || head.next == null) return true;        ListNode snake = head;        int len = 0;        // 计算长度,用时为O(n)        while (snake != null) {            len++;            snake = snake.next;        }        snake = head;  // 为了下一步的重新遍历        for (int i = 0; i < len / 2 - 1; i++) {            snake = snake.next;        }        // 对于1-2-3-4-4-3-2-1,此时snake到第一个4        // 对于1-2-3-2-1,此时snake到3        // 将后半部分进行反转,用时为O(n/2)        snake.next = reverse(snake.next);        ListNode snake2 = head;        snake = snake.next;        // 对未反转的前半部分和经过反转的后半部分进行逐个比较,用时为O(n/2)        for (int i = 0; i < len / 2; i++) {            if (snake2.val != snake.val) {                return false;            } else {                snake = snake.next;                snake2 = snake2.next;            }        }        return true;    }}
2 0