题解 | #反转链表#

https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca

这道题属于简单题,初学数据结构的同学们应该对此题非常熟悉。主要注意的地方在于,需要及时移动需要反转的节点的指针,保证翻转过程的指针指向不会断掉。
这里我提供的是Rust的实现代码,同学们可以按照自己的喜好换用其他语言。

/**
 *  #[derive(PartialEq, Eq, Debug, Clone)]
 *  pub struct ListNode {
 *      pub val: i32,
 *      pub next: Option<Box<ListNode>>
 *  }
 * 
 *  impl ListNode {
 *      #[inline]
 *      fn new(val: i32) -> Self {
 *          ListNode {
 *              val: val,
 *              next: None,
 *          }
 *      }
 *  }
 */

struct Solution{

}

impl Solution {
    fn new() -> Self {
        Solution{}
    }

    /**
    * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
    * 
        * @param head ListNode类 
        * @return ListNode类
    */
    pub fn ReverseList(&self, head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
        // write code here
        if head.is_none() {return None;}

        let mut prev = None;
        let mut current = head;
        while let Some(mut tmp) = current.take() {
            let next = tmp.next.take();
            tmp.next = prev.take();
            prev = Some(tmp);
            current = next;
        }

        prev
    }
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-09 12:11
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务