Category | Difficulty | Likes | Dislikes |
---|
algorithms | Easy (65.94%) | 758 | - |
Tags
linked-list
Companies
adobe
| amazon
| apple
| bloomberg
| facebook
| microsoft
| snapchat
| twitter
| uber
| yahoo
| yelp
| zenefits
反转一个单链表。
示例:
1
2
| 输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
|
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
Discussion | Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
| // 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>> {
let mut lhs = head;
let mut rhs = None;
while let Some(mut node) = lhs {
lhs = node.next.take();
node.next = rhs;
rhs = Some(node);
}
rhs
}
}
|