rustlang
May 20, 2024

How to reverse a list in RUST

Here we'll talking about how does reverse a list into RUST.

RUST

Usually if you want to reverse you need to create dummy and current variables for munipulate data:

let mut dummy = None;
let mut current = head;

Then you'll a cycle for iterate through the node's list:

while let Some(mut node) = current {}

Then you have to take a next node:

let next = node.next.take();

Then you need to set a next element as a dummy element:

node.next = dummy.take();

Now we need set dummy as a current node (which is already implementation of the first one and the dummy elements):

dummy = Some(node);

Finally we change current to the next (where next has already been taken as node.next)

current = next;

Code:

pub fn reverse_list(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
  let (mut dummy, mut current) = (None, head);
  
  while let Some(mut node) = current {
    let next = node.next.take();
    node.next = dummy.take();
    dummy = Some(node);
    current = next;
  }
  
  dummy
}