给定一个单链表的头结点pHead(该头节点是有值的,比如在下图,它的val是1),长度为n,反转该链表后,返回新链表的表头。
数据范围:
要求:空间复杂度
,时间复杂度
。
如当输入链表{1,2,3}时,
经反转后,原链表变为{3,2,1},所以对应的输出为{3,2,1}。
以上转换过程如下图所示:
{1,2,3}{3,2,1}{}{}空链表则输出空
/**
* #[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
let mut p1 = None;
let mut p2 = head;
// a -> b -> c
// p1 p2 p3
// target
// a <- b <- c
while p2.is_some() {
// unlink nodes
let mut p3 = p2.as_mut().unwrap().next.take();
// let mut p4 = p3.as_mut().unwrap().next.take();
// println!("{:?}", p2);
// println!("{:?}", p3);
// println!("{:?}", p4);
// make p1 <- p2, p3
p2.as_mut().unwrap().next = p1;
// move to next
p1 = p2;
p2 = p3;
// todo!();
}
// let mut p2 = head;
//let mut p3 =
// println!("{:?}", p2);
// println!("{:?}", head);
p1
}
} struct Solution{
}
impl Solution {
fn new() -> Self {
Solution{}
}
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* @param head ListNode类
* @return ListNode类
*/
pub fn ReverseList(&self, head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
let mut pre: Option<Box<ListNode>> = None;
let mut cur: Option<Box<ListNode>> = head;
// 获取当前节点
while let Some(mut node) = cur.take() {
// 当前节点移动到下一个节点: 先移动, 就不用暂存这个下一个节点了
// 这是因为while里面匹配了节点node, 就是cur, 相当于暂存了cur, 所以不用定义中间变量
cur = node.next;
// 当前节点的下一个节点指向前面, 反转
node.next = pre;
// 前一个移动到下一个节点
pre = Some(node);
}
pre
}
} Rust 尾插法:
pub fn ReverseList(&self, head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
// write code here
let mut res=None;
let mut cur=head;
while let Some(mut x)=cur{
cur=x.next;
x.next=res;
res=Some(x);
}
res
} Rust 递归写法:
pub fn ReverseList(&self, head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
// write code here
if let None=head{
return None;
}
let mut tmp=head.unwrap();
match tmp.next {
None=> return Some(tmp),
Some(mut x)=>{
tmp.next=None;
let mut flag=&mut x as *mut Box<ListNode>;
let last=self.ReverseList(Some(x));
unsafe {
(*flag).next=Some(tmp);
}
return last;
}
}
}
public class Solution { public static ListNode ReverseList(ListNode head) { if(head==null) return null; ListNode reversedHead=null; ListNode current=head; ListNode tmp=null; ListNode pre=null; while(current!=null){ tmp=current.next; current.next=pre; if(tmp==null) reversedHead=current; pre=current; current=tmp; } return reversedHead; } }