2487. 从链表中移除节点

2487. 从链表中移除节点

解法一: 递归

go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func removeNodes(head *ListNode) *ListNode {
if head == nil {
return nil
}
next := removeNodes(head.Next)
if next == nil || head.Val >= next.Val {
head.Next = next
return head
}
return next
}

解法二: 单调栈

go
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
29
30
31
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func removeNodes(head *ListNode) *ListNode {
stack := []*ListNode{}
node := head
for node != nil {
stack = append(stack, node)
node = node.Next
}
pre := -1
p := &ListNode{
Val: -1,
Next: nil,
}
for len(stack) > 0 {
node = stack[len(stack) - 1]
if node.Val >= pre {
pre = node.Val
tmp := p.Next
p.Next = node
p.Next.Next = tmp
}
stack = stack[:len(stack) - 1]
}
return p.Next
}

解法三: 反转链表

go
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func removeNodes(head *ListNode) *ListNode {
revertHead := revertLinkNode(head)
node := revertHead
p := &ListNode{
Val: -1,
Next: nil,
}
pre := p
for node != nil {
if pre.Val <= node.Val {
pre.Next = node
node = node.Next
pre = pre.Next
pre.Next = nil
} else {
node = node.Next
}
}
return revertLinkNode(p.Next)
}

func revertLinkNode(head *ListNode) *ListNode {
p := &ListNode{
Val: -1,
Next: nil,
}
node := head
for node != nil {
tmp := p.Next
p.Next = node
node = node.Next
p.Next.Next = tmp
}
return p.Next
}
作者

wuhunyu

发布于

2024-01-03

更新于

2024-01-03

许可协议