Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Definition for singly-linked list.
- #[derive(PartialEq, Eq, Debug)]
- pub struct ListNode {
- pub val: i32,
- pub next: Option<Box<ListNode>>,
- }
- impl ListNode {
- #[inline]
- pub fn new(val: i32) -> Self {
- ListNode { next: None, val }
- }
- pub fn from(s: &[i32]) -> Option<Box<Self>> {
- let mut new = None;
- let mut new_ref = &mut new;
- for e in s {
- *new_ref = Some(Box::new(ListNode::new(*e)));
- new_ref = &mut new_ref.as_mut().unwrap().next;
- }
- new
- }
- }
- pub fn copy(l: &Option<Box<ListNode>>) -> Option<Box<ListNode>> {
- fn reverse(mut l: &Option<Box<ListNode>>) -> Option<Box<ListNode>> {
- let mut rev = None;
- while let Some(inner) = l {
- rev = Some(Box::new(ListNode {
- val: inner.val,
- next: rev,
- }));
- l = &inner.next;
- }
- rev
- }
- reverse(&reverse(l))
- }
- pub fn copy2(l: &Option<Box<ListNode>>) -> Option<Box<ListNode>> {
- fn copy_to(to: &mut Option<Box<ListNode>>, from: &Option<Box<ListNode>>) {
- if let Some(inner) = from {
- *to = Some(Box::new(ListNode::new(inner.val)));
- copy_to(&mut to.as_mut().unwrap().next, &inner.next);
- }
- }
- let mut copy = None;
- copy_to(&mut copy, l);
- copy
- }
- pub fn copy3(mut l: &Option<Box<ListNode>>) -> Option<Box<ListNode>> {
- let mut copy = None;
- let mut copy_ref = &mut copy;
- while let Some(inner) = l {
- *copy_ref = Some(Box::new(ListNode::new(inner.val)));
- l = &inner.next;
- copy_ref = &mut copy_ref.as_mut().unwrap().next;
- }
- copy
- }
- #[cfg(test)]
- mod tests {
- use crate::*;
- #[test]
- fn it_works() {
- let s = [1, 2, 3];
- for i in 0..s.len() {
- let l = ListNode::from(&s[0..i]);
- assert_eq!(l, copy(&l));
- assert_eq!(l, copy2(&l));
- assert_eq!(l, copy3(&l));
- }
- }
- }
Add Comment
Please, Sign In to add comment