206. 反转链表
题目描述
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
解题思路
这就很简单了,一边出栈 一边入
#![allow(unused)] fn main() { struct Solution {} // Definition for singly-linked list. #[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 } } } impl Solution { pub fn reverse_list(mut head: Option<Box<ListNode>>) -> Option<Box<ListNode>> { let mut dummy = Box::new(ListNode { val: 0, next: None }); while let Some(mut node) = head { let tmp = dummy.next.take(); let n = node.next.take(); node.next = tmp; dummy.next = Some(node); head = n; } dummy.next } } }
学习感想
所以我这个算是什么方式
#![allow(unused)] fn main() { struct Solution {} // Definition for singly-linked list. #[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 } } } impl Solution { pub fn reverse_list(mut head: Option<Box<ListNode>>) -> Option<Box<ListNode>> { let mut res: Option<Box<ListNode>> = None; while let Some(mut x) = head { head = x.next.take(); x.next = res; res = Some(x); } res } } }