码迷,mamicode.com
首页 > 其他好文 > 详细

234. 回文链表 Palindrome Linked List

时间:2017-04-01 23:46:32      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:nod   for   lang   rgb   回文串   size   term   node   href   

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

标签:nod   for   lang   rgb   回文串   size   term   node   href   

原文地址:http://www.cnblogs.com/xiejunzhao/p/1e03825ea7dcdcd46b231981025cdb21.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!