234. 回文链表 Palindrome Linked List
Posted Long Long Journey
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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?
判断一个链表是否为回文串
思路:1.找到中间点,2.反转后半部分链表,3.判断前半部分与后半部分是否相同
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode ReverseList(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode nextNode = head.next;
ListNode newHead = ReverseList(nextNode);
nextNode.next = head;
head.next = null;
return newHead;
}
public ListNode FindMid(ListNode head) {
ListNode fast = head;
ListNode slow = head;
int num = 1;
while (fast != null) {
num++;
if (fast.next != null) {
fast = fast.next.next;
} else {
break;
}
slow = slow.next;
}
return slow;
}
public bool IsPalindrome(ListNode head) {
if (head == null) {
return true;
}
ListNode midNode = FindMid(head);
ListNode newMid = ReverseList(midNode);
ListNode font = head;
ListNode back = newMid;
while (back != null) {
if (font.val != back.val) {
return false;
}
font = font.next;
back = back.next;
}
return true;
}
}
以上是关于234. 回文链表 Palindrome Linked List的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 234 Palindrome Linked List(回文链表)(*)(?)
LeetCode 234. Palindrome Linked List (回文链表)
LeetCode 234. 回文链表 Palindrome Linked List (Easy)
LeetCode 234 Palindrome Linked List(回文链表)(*)(?)