给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
示例 1:

Input: head = [1,2,3,4,5]Output: [5,4,3,2,1]
示例 2:

Input: head = [1,2]Output: [2,1]
示例 3:
Input: head = []Output: []
提示:
- 链表中节点的数目范围是
[0, 5000] - -5000 ≤
Node.val≤ 5000
思路
链表可以选用迭代或递归方式完成反转。本次我们采用迭代的方法完成反转链表。
新建三个指针:prev、cur、next,它们分别指向前一个节点、当前节点、下一个节点。迭代条件是while( next != nullptr ),我们就一直进行反转链表的操作。
反转链表只需要模拟整个过程,推荐在画板上先画出整个过程,然后再编码。
代码
Cpp:
// 4ms, 8MB/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode() : val(0), next(nullptr) {}* ListNode(int x) : val(x), next(nullptr) {}* ListNode(int x, ListNode *next) : val(x), next(next) {}* };*/class Solution {public:ListNode* reverseList(ListNode* head) {if( head == nullptr ) return nullptr;ListNode* prev = nullptr;ListNode* cur = head;ListNode* next = head->next;while( next != nullptr ) {cur->next = prev;prev = cur;cur = next;next = next->next;}cur->next = prev;return cur;}};
Rust:
// 0ms, 2.3MB// 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(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {if let None = head {return None;}let mut prev: Option<Box<ListNode>> = None;let mut curr: Option<Box<ListNode>> = head;while curr.is_some() {let mut tmp_node = curr.take().unwrap();curr = tmp_node.next;tmp_node.next = prev;prev = Some(tmp_node);}prev}}
