Skip to content

Commit 42bc09f

Browse files
committed
📝 add lc 92
1 parent b230723 commit 42bc09f

File tree

2 files changed

+98
-1
lines changed

2 files changed

+98
-1
lines changed

Java/alg/README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,8 @@
130130
- [82.删除排序链表中的重复元素2](lc/82.删除排序链表中的重复元素2.md)
131131
- [86.分隔链表](lc/86.分隔链表.md)
132132
- [90.子集2](lc/90.子集2.md)
133-
- [91.解码方法](lc/91. 解码方法.md)
133+
- [91.解码方法](lc/91.解码方法.md)
134+
- [92.反转链表2](92.反转链表2.md)
134135

135136
## 笔试
136137

Java/alg/lc/92.反转链表2.md

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
# 92. 反转链表 II
2+
3+
[url](https://leetcode-cn.com/problems/reverse-linked-list-ii/)
4+
5+
## 题目
6+
7+
给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。
8+
9+
[](https://assets.leetcode.com/uploads/2021/02/19/rev2ex2.jpg)
10+
11+
12+
```
13+
输入:head = [1,2,3,4,5], left = 2, right = 4
14+
输出:[1,4,3,2,5]
15+
输入:head = [5], left = 1, right = 1
16+
输出:[5]
17+
```
18+
19+
## 方法
20+
21+
22+
## code
23+
24+
### js
25+
26+
```js
27+
let reverseBetween = (head, m, n) => {
28+
let p = head;
29+
let idx = 1;
30+
let stack = [];
31+
while (p != null) {
32+
if (idx >= m && idx <= n)
33+
stack.push(p.val)
34+
idx++
35+
p = p.next;
36+
}
37+
idx = 1;
38+
p = head;
39+
while (p != null) {
40+
if (idx >= m && idx <= n)
41+
p.val = stack.pop();
42+
idx++;
43+
p = p.next;
44+
}
45+
return head;
46+
}
47+
```
48+
49+
### go
50+
51+
```go
52+
func reverseBetween(head *ListNode, m int, n int) *ListNode {
53+
dummy := &ListNode{}
54+
dummy.Next = head
55+
pre, cur, next := dummy, &ListNode{}, &ListNode{}
56+
for i := 1; i < m; i++ {
57+
pre = pre.Next
58+
}
59+
cur = pre.Next
60+
for i := m; i < n; i++ {
61+
next = cur.Next
62+
cur.Next = next.Next
63+
next.Next = pre.Next
64+
pre.Next = next
65+
}
66+
return dummy.Next
67+
}
68+
```
69+
70+
### java
71+
72+
```java
73+
class Solution {
74+
public ListNode reverseBetween(ListNode head, int m, int n) {
75+
ListNode p = head;
76+
int idx = 1;
77+
Stack<Integer> stack = new Stack<>();
78+
while (p != null) {
79+
if (idx >= m && idx <= n)
80+
stack.push(p.val);
81+
idx++;
82+
p = p.next;
83+
}
84+
idx = 1;
85+
p = head;
86+
while (p != null) {
87+
if (idx >= m && idx <= n)
88+
p.val = stack.pop();
89+
idx++;
90+
p = p.next;
91+
}
92+
return head;
93+
}
94+
}
95+
```
96+

0 commit comments

Comments
 (0)