Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,844 questions

55,671 answers

573 users

How to reverse a singly linked list in-place in Rust

1 Answer

0 votes
// A singly linked list node.
// Each node owns the next node through Box<T>.

struct ListNode {
    value: i32,
    next: Option<Box<ListNode>>,
}

// Reverse the linked list in-place.
// This consumes the head and returns the new head.
fn reverse_list(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
    let mut prev: Option<Box<ListNode>> = None;
    let mut current = head;

    while let Some(mut node) = current {
        // Take ownership of node.next
        let next = node.next.take();

        // Reverse the pointer
        node.next = prev;

        // Move prev and current forward
        prev = Some(node);
        current = next;
    }

    prev
}

// Print the linked list
fn print_list(head: &Option<Box<ListNode>>) {
    let mut temp = head.as_ref();

    while let Some(node) = temp {
        print!("{}", node.value);
        if node.next.is_some() {
            print!(" -> ");
        }
        temp = node.next.as_ref();
    }

    println!();
}

fn main() {
    // Build list: 1 -> 2 -> 3 -> 4 -> 5
    let mut head = Some(Box::new(ListNode {
        value: 1,
        next: Some(Box::new(ListNode {
            value: 2,
            next: Some(Box::new(ListNode {
                value: 3,
                next: Some(Box::new(ListNode {
                    value: 4,
                    next: Some(Box::new(ListNode {
                        value: 5,
                        next: None,
                    })),
                })),
            })),
        })),
    }));

    println!("Original list:");
    print_list(&head);

    // Reverse the list
    head = reverse_list(head);

    println!("Reversed list:");
    print_list(&head);
}


/*
run:

Original list:
1 -> 2 -> 3 -> 4 -> 5
Reversed list:
5 -> 4 -> 3 -> 2 -> 1

*//

 



answered Jun 30 by avibootz
...