- 已经连续三次记录双指针专题,不得不再说,Rust性能确实强得有点离谱啊....
目录
一、876 - 链表的中间结点
给定一个头结点为 head 的非空单链表,返回链表的中间结点。
如果有两个中间结点,则返回第二个中间结点。
示例 1:
输入:[1,2,3,4,5]
输出:此列表中的结点 3 (序列化形式:[3,4,5])
返回的结点值为 3 。 (测评系统对该结点序列化表述是 [3,4,5])。
注意,我们返回了一个 ListNode 类型的对象 ans,这样:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, 以及 ans.next.next.next = NULL.
示例 2:输入:[1,2,3,4,5,6]
输出:此列表中的结点 4 (序列化形式:[4,5,6])
由于该列表有两个中间结点,值分别为 3 和 4,我们返回第二个结点。
提示:
给定链表的结点数介于 1 和 100 之间。
链接:力扣https://leetcode.cn/problems/middle-of-the-linked-list/
- C语言
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* middleNode(struct ListNode* head){
struct ListNode* p = head;
struct ListNode* q = head;
while (q->next && q->next->next) {
p = p->next;
q = q->next->next;
}
if (q->next)
p = p->next;
return p;
}
- Rust
// 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 middle_node(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
let mut fast = &head;
let mut slow = &head;
while fast.is_some() && fast.as_ref().unwrap().next.is_some() {
slow = &slow.as_ref().unwrap().next;
fast = &fast.as_ref().unwrap().next;
fast = &fast.as_ref().unwrap().next;
}
slow.clone()
}
}
二、19 - 删除链表的倒数第N个结点
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
示例 1:
输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
示例 2:输入:head = [1], n = 1
输出:[]
示例 3:输入:head = [1,2], n = 1
输出:[1]
提示:
链表中结点的数目为 sz
1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz
链接:力扣https://leetcode.cn/problems/remove-nth-node-from-end-of-list/
- C语言
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
struct ListNode* init = malloc(sizeof(struct ListNode));
init->val = 0, init->next = head;
struct ListNode* first = head;
struct ListNode* second = init;
for (int i = 0; i < n; i++) {
first = first->next;
}
while (first) {
first = first->next;
second = second->next;
}
second->next = second->next->next;
struct ListNode* ans = init->next;
free(init);
return ans;
}
- Rust
impl Solution {
pub fn remove_nth_from_end(head: Option<Box<ListNode>>, n: i32) -> Option<Box<ListNode>> {
let mut init = Box::new(ListNode { val: 0, next: head });
unsafe {
let mut slow = &mut init as *mut Box<ListNode>;
let mut fast = &mut init as *mut Box<ListNode>;
// move fast n forward
for _ in 0..n {
fast = (*fast).next.as_mut().unwrap();
}
while (*fast).next.is_some() {
fast = (*fast).next.as_mut().unwrap();
slow = (*slow).next.as_mut().unwrap();
}
(*slow).next = (*slow).next.take().unwrap().next;
}
init.next
}
}
每一个不曾起舞的日子,都是对生命的辜负。