Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 578ee6c

Browse files
committed
solve 92.反转链表-ii
1 parent 888cc04 commit 578ee6c

File tree

1 file changed

+89
-0
lines changed

1 file changed

+89
-0
lines changed

‎zh/92.反转链表-ii.java‎

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
/*
2+
* @lc app=leetcode.cn id=92 lang=java
3+
*
4+
* [92] 反转链表 II
5+
*
6+
* https://leetcode-cn.com/problems/reverse-linked-list-ii/description/
7+
*
8+
* algorithms
9+
* Medium (54.28%)
10+
* Likes: 1018
11+
* Dislikes: 0
12+
* Total Accepted: 205K
13+
* Total Submissions: 374.3K
14+
* Testcase Example: '[1,2,3,4,5]\n2\n4'
15+
*
16+
* 给你单链表的头指针 head 和两个整数 left 和 right ,其中 left 。请你反转从位置 left 到位置 right 的链表节点,返回
17+
* 反转后的链表 。
18+
*
19+
*
20+
* 示例 1:
21+
*
22+
*
23+
* 输入:head = [1,2,3,4,5], left = 2, right = 4
24+
* 输出:[1,4,3,2,5]
25+
*
26+
*
27+
* 示例 2:
28+
*
29+
*
30+
* 输入:head = [5], left = 1, right = 1
31+
* 输出:[5]
32+
*
33+
*
34+
*
35+
*
36+
* 提示:
37+
*
38+
*
39+
* 链表中节点数目为 n
40+
* 1
41+
* -500
42+
* 1
43+
*
44+
*
45+
*
46+
*
47+
* 进阶: 你可以使用一趟扫描完成反转吗?
48+
*
49+
*/
50+
51+
// @lc code=start
52+
/**
53+
* Definition for singly-linked list.
54+
* public class ListNode {
55+
* int val;
56+
* ListNode next;
57+
* ListNode() {}
58+
* ListNode(int val) { this.val = val; }
59+
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
60+
* }
61+
*/
62+
class Solution {
63+
public ListNode reverseBetween(ListNode head, int left, int right) {
64+
ListNode dummy = new ListNode(0);
65+
dummy.next = head;
66+
67+
ListNode preLeftNode = dummy;
68+
for (int i = 1; i < left; i++) {
69+
preLeftNode = preLeftNode.next;
70+
}
71+
ListNode leftNode = preLeftNode.next;
72+
73+
ListNode prev = leftNode;
74+
ListNode curr = leftNode.next;
75+
for (int i = left; i < right; i++) {
76+
ListNode next = curr.next;
77+
curr.next = prev;
78+
prev = curr;
79+
curr = next;
80+
}
81+
82+
leftNode.next = curr;
83+
preLeftNode.next = prev;
84+
85+
return dummy.next;
86+
}
87+
}
88+
// @lc code=end
89+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /