Java [Leetcode 234]palindrome Linked List

Source: Internet
Author: User

Title Description:

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

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

Problem Solving Ideas:

The time complexity of using O (n) and the time Complexity of O (1) indicate that the sequential traversal of the linked list does not open up the space that is equivalent to the linked list, so that the middle position can be found, then the second half of the list is reversed, and then the list of the front half is positioned one by one.

The code is as follows:

/** * Definition for singly-linked list. * public class ListNode {*     int val; *     ListNode Next; *     listnode (int x) {val = x;}}} */public class Soluti On {public    Boolean ispalindrome (ListNode head) {        ListNode end = head;        ListNode mid = head;        while (end! = NULL && End.next = null) {        end = End.next.next;        MID = Mid.next;        }        if (end! = null)//in case of odd list        mid = Mid.next;        MID = Reverselist (mid);        while (Mid! = null) {        if (mid.val! = Head.val)        return false;        MID = Mid.next;        head = Head.next;        }        return true;    }    Public ListNode reverselist (ListNode head) {    ListNode pre = null, next = NULL;    while (head! = null) {    next = Head.next;    Head.next = pre;    Pre = head;    Head = Next;    }    return pre;    }}

  

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