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.判断前半部分与后半部分是否相同

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * public int val;
  5. * public ListNode next;
  6. * public ListNode(int x) { val = x; }
  7. * }
  8. */
  9. public class Solution {
  10. public ListNode ReverseList(ListNode head) {
  11. if (head == null || head.next == null)
  12. return head;
  13. ListNode nextNode = head.next;
  14. ListNode newHead = ReverseList(nextNode);
  15. nextNode.next = head;
  16. head.next = null;
  17. return newHead;
  18. }
  19. public ListNode FindMid(ListNode head) {
  20. ListNode fast = head;
  21. ListNode slow = head;
  22. int num = 1;
  23. while (fast != null) {
  24. num++;
  25. if (fast.next != null) {
  26. fast = fast.next.next;
  27. } else {
  28. break;
  29. }
  30. slow = slow.next;
  31. }
  32. return slow;
  33. }
  34. public bool IsPalindrome(ListNode head) {
  35. if (head == null) {
  36. return true;
  37. }
  38. ListNode midNode = FindMid(head);
  39. ListNode newMid = ReverseList(midNode);
  40. ListNode font = head;
  41. ListNode back = newMid;
  42. while (back != null) {
  43. if (font.val != back.val) {
  44. return false;
  45. }
  46. font = font.next;
  47. back = back.next;
  48. }
  49. return true;
  50. }
  51. }





以上是关于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(回文链表)(*)(?)

234. Palindrome Linked List(回文链表)

234. Palindrome Linked ListEasy判断链表是否回文