Advertisement
Guest User

Untitled

a guest
Aug 19th, 2019
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1. #[derive(PartialEq, Eq, Clone, Debug)]
  2. pub struct ListNode {
  3. pub val: i32,
  4. pub next: Option<Box<ListNode>>
  5. }
  6.  
  7. impl ListNode {
  8. #[inline]
  9. fn new(val: i32) -> Self {
  10. ListNode {
  11. next: None,
  12. val
  13. }
  14. }
  15. }
  16.  
  17. struct Solution {}
  18. impl Solution {
  19. pub fn is_palindrome(mut head: Option<Box<ListNode>>) -> bool {
  20. let mut dummy = &head;
  21. let mut len: usize = 0;
  22. while dummy.is_some() {
  23. len += 1;
  24. dummy = &dummy.as_ref().unwrap().next;
  25. }
  26.  
  27. if len <= 1 { return true; }
  28.  
  29. let mut first = &mut head;
  30. let mut second;
  31. let mid = len / 2;
  32.  
  33. for _ in 1..mid {
  34. first = &mut first.as_mut().unwrap().next;
  35. }
  36.  
  37. if len % 2 == 0 {
  38. second = first.as_mut().unwrap().next.take();
  39. } else {
  40. // remove the middle node
  41. let tmp = first.as_mut().unwrap().next.take();
  42. second = tmp.unwrap().next.take();
  43. }
  44.  
  45. // now reverse first linked list
  46. let mut prev = None;
  47. let mut cur = head;
  48. let mut next;
  49. while cur.is_some() {
  50. let mut node = cur.unwrap();
  51. next = node.next.take();
  52. node.next = prev;
  53. prev = Some(node);
  54. cur = next;
  55. }
  56.  
  57. // now compare first and second
  58. // note that prev becomes the head node of first
  59. while prev.is_some() && second.is_some() {
  60. let node1 = prev.unwrap();
  61. let node2 = second.unwrap();
  62. if node1.val != node2.val {
  63. return false;
  64. } else {
  65. prev = node1.next;
  66. second = node2.next;
  67. }
  68. }
  69.  
  70. // prev.is_none() && second.is_none()
  71. true
  72. }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement