Guest User

Untitled

a guest
Feb 15th, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. // Definition for singly-linked list.
  2. #[derive(PartialEq, Eq, Debug)]
  3. pub struct ListNode {
  4. pub val: i32,
  5. pub next: Option<Box<ListNode>>,
  6. }
  7.  
  8. impl ListNode {
  9. #[inline]
  10. pub fn new(val: i32) -> Self {
  11. ListNode { next: None, val }
  12. }
  13.  
  14. pub fn from(s: &[i32]) -> Option<Box<Self>> {
  15. let mut new = None;
  16. let mut new_ref = &mut new;
  17. for e in s {
  18. *new_ref = Some(Box::new(ListNode::new(*e)));
  19. new_ref = &mut new_ref.as_mut().unwrap().next;
  20. }
  21. new
  22. }
  23. }
  24.  
  25. pub fn copy(l: &Option<Box<ListNode>>) -> Option<Box<ListNode>> {
  26. fn reverse(mut l: &Option<Box<ListNode>>) -> Option<Box<ListNode>> {
  27. let mut rev = None;
  28. while let Some(inner) = l {
  29. rev = Some(Box::new(ListNode {
  30. val: inner.val,
  31. next: rev,
  32. }));
  33. l = &inner.next;
  34. }
  35. rev
  36. }
  37.  
  38. reverse(&reverse(l))
  39. }
  40.  
  41. pub fn copy2(l: &Option<Box<ListNode>>) -> Option<Box<ListNode>> {
  42. fn copy_to(to: &mut Option<Box<ListNode>>, from: &Option<Box<ListNode>>) {
  43. if let Some(inner) = from {
  44. *to = Some(Box::new(ListNode::new(inner.val)));
  45. copy_to(&mut to.as_mut().unwrap().next, &inner.next);
  46. }
  47. }
  48.  
  49. let mut copy = None;
  50. copy_to(&mut copy, l);
  51. copy
  52. }
  53.  
  54. pub fn copy3(mut l: &Option<Box<ListNode>>) -> Option<Box<ListNode>> {
  55. let mut copy = None;
  56. let mut copy_ref = &mut copy;
  57. while let Some(inner) = l {
  58. *copy_ref = Some(Box::new(ListNode::new(inner.val)));
  59. l = &inner.next;
  60. copy_ref = &mut copy_ref.as_mut().unwrap().next;
  61. }
  62. copy
  63. }
  64.  
  65. #[cfg(test)]
  66. mod tests {
  67. use crate::*;
  68. #[test]
  69. fn it_works() {
  70. let s = [1, 2, 3];
  71. for i in 0..s.len() {
  72. let l = ListNode::from(&s[0..i]);
  73. assert_eq!(l, copy(&l));
  74. assert_eq!(l, copy2(&l));
  75. assert_eq!(l, copy3(&l));
  76. }
  77. }
  78. }
Add Comment
Please, Sign In to add comment