Java for Leetcode 234 palindrome Linked List

Source: Internet
Author: User

Problem Solving Ideas:

The spatial complexity of O (1) means that the problem cannot be solved by opening a list. We can divide the list into front and back two parts, and the second half is flipped by the reciprocal assignment of pointers.

The Java implementation is as follows:

public static Boolean Ispalindrome (ListNode head) {if (head = = NULL | | head.next = = NULL) return true; ListNode middle = head, fast = Head;while (FAST! = NULL && Fast.next! = null) {middle = Middle.next;fast = Fast.ne Xt.next;} ListNode righthalf = Reverselistnode (middle), while (righthalf! = null) {if (righthalf.val! = head.val) Return false;head = Head.next;righthalf = Righthalf.next;} return true;} public static ListNode Reverselistnode (ListNode head) {if (head = = NULL | | head.next = = NULL) return head;  ListNode pre = head, cur = head.next, tmp = Head;head.next = Null;while (cur! = null) {tmp = Cur.next;cur.next = Pre;pre = Cur;cur = tmp;} return pre;}

Java for 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.