【LeetCode】234 Palindrome Linked List

原创 2015年07月10日 16:33:05
Palindrome Linked List
Total Accepted: 1116 Total Submissions: 4295 My Submissions Question Solution 
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?
Hide Tags Linked List Two Pointers
【解题思路】
1、遍历链表,快慢指针,找到链表后半部分。
2、反转链表,可以参考Reverse Linked List
3、然后比较前半部分和后半部分的val值。

Java AC

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isPalindrome(ListNode head) {
        if (head == null) {
            return true;
        }
        ListNode slow = head;
        ListNode fast = slow.next;
        while (fast != null && fast.next != null && fast.next.next != null){
            slow = slow.next;
            fast = fast.next.next;
        }
        ListNode p = slow.next;
        ListNode q;
        ListNode end = null;
        while (p != null) {
            q = p.next;
            p.next = end;
            end = p;
            p = q;
        }
        while (head != null && end != null) {
            if (head.val != end.val) {
                return false;
            }
            head = head.next;
            end = end.next;
        }
        return true;
    }
}


相关文章推荐

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-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

思路: 1、遍历整个链表,将链表每个节点的值记录在数组中,再判断数组是不是一个回文数组,时间复杂度为O(n),但空间复杂度也为O(n),不满足空间复杂度要求。 2、利用栈先进后出的性质,将链表前半段压...

[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)...

Leetcode_234_Palindrome Linked List

本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/47334465 Given a singly lin...

LeetCode笔记:234. Palindrome Linked List

判断一个链表是否是回文

leetcode234~Palindrome Linked List

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

[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
举报原因:
原因补充:

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