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