I want to build palindrom checker in Rust, the constraint is O(n) time with 0(1) additional space. My ideas are:
-
Get the middle of the linked list.
-
Reverse the second half of the linked list.
-
Check if the first half and second half are identical.
fn isListPalindrome(l: ListNode<i32>) -> bool { let mut fastPointer = &l; let mut slowPointer = &l; let mut midIndex = 0; // here first step loop { match fastPointer { Some(n) => { if let Some(nn) = &n.next { fastPointer = &nn.next; } else { break; } midIndex += 1; }, None => break } match slowPointer { Some(n) => { slowPointer = &n.next }, None => break } } if let Some(_fp) = &fastPointer { slowPointer = &fastPointer; } // here is second step to reverse list let mut prev = None; while let Some(n) = slowPointer { let next = &n.next; n.next = prev.take(); println!("{:?}", n); prev = &n; slowPointer = next; } true }
but got error
note: expected reference
&std::option::Option<std::boxed::Box<List<i32>>>
found reference&&std::boxed::Box<List<i32>>
How to reverse list in Rust ? I dont want to create variable list for prev, because it will not make 0(1) additional space
Thanks
https://stackoverflow.com/questions/65769092/rust-revese-list January 18, 2021 at 01:06PM
没有评论:
发表评论