【LeetCode】234 Palindrome Linked List

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 链表
所属专栏: LeetCode解题报告
上一篇【九度】抓取九度AC所有代码以及在CSDN的解题思路链接形成文件提交至github
下一篇【LeetCode】235 Lowest Common Ancestor of a Binary Search Tree
想对作者说点什么? 我来说一句

leetcode141&234

1、 Linked List Cycle

Ekinnn Ekinnn

2017-01-13 19:51:43

阅读数:174

没有更多推荐了,返回首页

关闭
关闭