Rust每日一题(10)---数据结构-链表--reverse-linked-list
leetcode地址 给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
示例 1:
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
示例 2:
输入:head = [1,2]
输出:[2,1]
示例 3:
输入:head = []
输出:[]
难度: 简单
核心还是分析关键操作步骤,有两种思路:
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ListNode {
pub val: i32,
pub next: Option<Box<ListNode>>
}
impl ListNode {
#[inline]
fn new(val: i32) -> Self {
ListNode {
next: None,
val
}
}
}
pub fn reverse_list(mut head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
let mut prev = None;
while let Some(mut temp) = head.take() {
let next_temp = temp.next.take();
temp.next = prev;
head = next_temp;
prev = Some(temp);
}
prev
}
//
fn main(){
let list = vec![1,2,3,4,5];
let mut head = Some(Box::new(ListNode::new(list[0])));
let mut curr = head.as_mut();
for i in 1..list.len() {
if let Some(mut node) = curr.take() {
node.next = Some(Box::new(ListNode::new(list[i])));
curr = node.next.as_mut();
}
}
println!("{:?}", reverse_list(head));
}
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!