Leetcode 234. Palindrome Linked List
Posted Deribs4
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 234. Palindrome Linked List相关的知识,希望对你有一定的参考价值。
Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?
Similar Questions
Palindrome Number Valid Palindrome Reverse Linked List
Next challenges
思路:3步走。
1.设置fast和slow指针,使得fast遍历列表后,slow位于列表中偏右部。
2.反转slow侧的列表。
3.将fast指向head,依次比较slow侧的列表和fast侧列表每个元素的值。
代码:上述1和2的2个操作还是比较经典的。
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 public boolean isPalindrome(ListNode head) { 11 ListNode fast = head, slow = head; 12 // 每1次fast都比slow多走1个单位直到fast不能再1次走2步为止 13 while(fast != null && fast.next != null) { 14 slow = slow.next; 15 fast = fast.next.next; 16 } 17 if(fast != null) {//有奇数个node,设置slow侧的node数量少于fast侧的node数量 18 slow = slow.next; 19 } 20 slow = reverse(slow);//slow侧列表反转 21 fast = head; 22 while(slow != null && slow.val == fast.val) { 23 slow = slow.next; 24 fast = fast.next; 25 } 26 return slow == null; 27 } 28 29 //列表反转 30 public ListNode reverse(ListNode head) { 31 ListNode prev = null; 32 while(head != null) { 33 ListNode next = head.next; 34 head.next = prev; 35 prev = head; 36 head = next; 37 } 38 return prev; 39 } 40 }
以上是关于Leetcode 234. Palindrome Linked List的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode 234. Palindrome Linked List
Java [Leetcode 234]Palindrome Linked List
LeetCode 234. Palindrome Linked List
leetcode 234. Palindrome Linked List