Skip to content

Commit 9f2a44d

Browse files
committed
add 1019
1 parent 66d68c8 commit 9f2a44d

File tree

3 files changed

+77
-0
lines changed

3 files changed

+77
-0
lines changed
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
[package]
2+
name = "S1019-next-greater-node-in-linked-list"
3+
version = "0.1.0"
4+
authors = ["xargin <cao1988228@163.com>"]
5+
edition = "2018"
6+
7+
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
8+
9+
[dependencies]
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
单调栈
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
fn main() {
2+
println!("Hello, world!");
3+
}
4+
5+
/*
6+
* @lc app=leetcode.cn id=1019 lang=rust
7+
*
8+
* [1019] 链表中的下一个更大节点
9+
*/
10+
// Definition for singly-linked list.
11+
// #[derive(PartialEq, Eq, Clone, Debug)]
12+
// pub struct ListNode {
13+
// pub val: i32,
14+
// pub next: Option<Box<ListNode>>
15+
// }
16+
//
17+
// impl ListNode {
18+
// #[inline]
19+
// fn new(val: i32) -> Self {
20+
// ListNode {
21+
// next: None,
22+
// val
23+
// }
24+
// }
25+
// }
26+
impl Solution {
27+
fn count_len(head: Option<Box<ListNode>>) -> (i32, Vec<i32>) {
28+
let mut head = head;
29+
let mut cursor = &mut head;
30+
let mut cnt = 0;
31+
let mut v = vec![];
32+
loop {
33+
match cursor {
34+
Some(e) => {
35+
cursor = &mut e.next;
36+
cnt += 1;
37+
v.push(e.val);
38+
}
39+
None => break,
40+
}
41+
}
42+
(cnt, v)
43+
}
44+
45+
pub fn next_larger_nodes(head: Option<Box<ListNode>>) -> Vec<i32> {
46+
let mut stack = vec![];
47+
//let mut index_arr = vec![];
48+
let (cnt, v) = Self::count_len(head);
49+
let mut res = vec![];
50+
(0..cnt).for_each(|_| res.push(0));
51+
for (idx, v) in v.iter().enumerate() {
52+
if stack.is_empty() {
53+
stack.push((v, idx));
54+
continue;
55+
}
56+
57+
while !stack.is_empty() && stack.last().unwrap().0 < v {
58+
let (_, i) = stack.pop().unwrap();
59+
res[i] = *v;
60+
}
61+
stack.push((v, idx));
62+
}
63+
res
64+
}
65+
}
66+
67+

0 commit comments

Comments
 (0)