leetcode解题报告234——Palindrome Linked List

原创 2015年07月10日 09:33:38

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

思路:用快慢指针去得到链表的中心位置。
用一个栈去装链表的前半部分。
注意链表奇数偶数的情况。

解法:

package linkedlist;

import java.util.Stack;

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

public class PalindromeLinkedList {
    public boolean isPalindrome(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        Stack<Integer> stack = new Stack<Integer>();

        while (fast != null && fast.next != null) {
            stack.push(slow.val);
            slow = slow.next;
            fast = fast.next.next;
        }

        if (fast != null) {
            slow = slow.next;
        }

        while (slow != null) {
            if (slow.val != stack.pop()) {
                return false;
            }
            slow = slow.next;
        }
        return true;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

    }

}
版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

Leetcode——234. Palindrome Linked List

题目Given a singly linked list, determine if it is a palindrome.Follow up: Could you do it in O(n) ti...

[LeetCode-234] Palindrome Linked List(回文链表、链表中间节点查找)

Given a singly linked list, determine if it is a palindrome. Follow up: Could you do it in O(n) tim...

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

Given a singly linked list, determine if it is a palindrome.Follow up:Could you do it in O(n) time a...

Leetcode 234. Palindrome Linked List

234. Palindrome Linked List Total Accepted: 69120 Total Submissions: 225579 Difficulty: Easy ...

(LeetCode 234)Palindrome Linked List

Leetcode第234题目是Palindrome Linked List。题目的描述如下: Given a singly linked list, determine if it is a pali...

[leetcode]114. Flatten Binary Tree to Linked List@Java解题报告

https://leetcode.com/problems/flatten-binary-tree-to-linked-list/description/ Given a bin...

【LeetCode】Reverse Linked List 解题报告

Reverse Linked List[LeetCode]https://leetcode.com/problems/reverse-linked-list/Total Accepted: 10547...

LeetCode(114) Flatten Binary Tree to Linked List解题报告

Given a binary tree, flatten it to a linked list in-place.For example, Given 1 / \ ...

【LeetCode】206. Reverse Linked List 解题报告

转载请注明出处:http://blog.csdn.net/crazy1235/article/details/51820937Subject 出处:https://leetcode.com/pro...

LeetCode 92. Reverse Linked List II 解题报告

LeetCode 92. Reverse Linked List II 解题报告题目描述Reverse a linked list from position m to n. Do it in-pla...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)