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