Rust Program: Merge sorted singly linked lists
Write a Rust program to merge two sorted singly linked lists into one sorted linked list.
Sample Solution:
Rust Code:
Output:
Linked List: 1 -> 3 -> 5 -> None Linked List: 2 -> 4 -> 6 -> None Linked List: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> None
Explanation:
Here is a brief explanation of the above Rust code:
- Node structure:
- Defines a structure "Node" representing a node in a singly linked list.
- Each node contains an 'i32' value 'data' and an Option<Box<Node>> 'next', representing a pointer to the next node in the list.
- Node implementation:
- Implement associated functions for the "Node" structure.
- Provides a function "new()" to create a new node with the given data.
- Print List Function:
- Define a function "print_list()" to print the elements of a linked list.
- It takes a reference to the head of the list (&Option<Box<Node>>) as input.
- Iterates through the list, printing each node's data sequentially.
- Merge Sorted Lists Function:
- Defines a function "merge_sorted_lists()" to merge two sorted linked lists into one sorted linked list.
- It takes ownership of two sorted linked lists (l1 and l2) as input and returns a new sorted linked list.
- Merge the lists by comparing the data of the nodes and rearranging the pointers accordingly.
- Maintain a 'result' variable to store the merged list and a 'tail' pointer to keep track of the end of the merged list.
- Main function:
- Create two sorted linked lists (l1 and l2) with some predefined values.
- Prints the original lists using the "print_list()" function.
- Merges the lists using the "merge_sorted_lists()" function and print the merged list.
Rust Code Editor:
Previous: Rust Program: Finding Middle element of singly linked list.
Next: Rust Program: Remove duplicates from singly linked list.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics