Leetcode 234:palindrome Linked List

Source: Internet
Author: User

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

Follow up:
Could do it in O (n) time and O (1) space?


Ideas

The first is divided into two parts of the same size (possibly 1), reverse a list. and then compare.

[CODE]

/** * Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int x) {val = x;}} * *//1 2 3 2 1;        1 2 3 3 2 1;public class Solution {public boolean ispalindrome (ListNode head) {//input check ABCBA ABCCBA                if (Head==null | | head.next==null) return true;        ListNode middle = partition (head);                Middle = reverse (middle);            while (Head!=null && middle!=null) {if (head.val! = Middle.val) return false;            head = Head.next;        middle = middle.next;    } return true;        } private ListNode partition (ListNode head) {ListNode p = head;            while (P.next!=null && p.next.next!=null) {p = p.next.next;        head = Head.next;        } p = Head.next;        Head.next = null;    return p;     } Private ListNode reverse (ListNode head) {if (Head==null | | head.next==null) return head;   ListNode pre = head;        ListNode cur = head.next;        Pre.next = null;                ListNode NXT = null;            while (cur!=null) {nxt = Cur.next;            Cur.next = pre;            Pre = cur;        cur = NXT;    } return pre; }}



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Leetcode 234:palindrome Linked List

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.