File tree Expand file tree Collapse file tree 2 files changed +80
-0
lines changed Expand file tree Collapse file tree 2 files changed +80
-0
lines changed Original file line number Diff line number Diff line change 1+ function ListNode ( val ) {
2+ this . val = val
3+ this . next = null
4+ }
5+
6+ module . exports = ListNode
Original file line number Diff line number Diff line change 1+ /**
2+ * Definition for singly-linked list.
3+ * function ListNode(val) {
4+ * this.val = val;
5+ * this.next = null;
6+ * }
7+ */
8+
9+ const ListNode = require ( "../工具/链表" )
10+ /**
11+ * @param {ListNode } head
12+ * @param {number } m
13+ * @param {number } n
14+ * @return {ListNode }
15+ */
16+
17+ let reverseBetween = function ( head , m , n ) {
18+ let i = 1
19+ let sliceStartPrev = null
20+ let sliceStart = null
21+ let sliceEnd = null
22+ let cur = head
23+
24+ // 记录切分起点的前一个节点,和切分终点的后一个节点
25+ while ( i <= n ) {
26+ if ( i === m - 1 ) {
27+ sliceStartPrev = cur
28+ }
29+ if ( i === m ) {
30+ sliceStart = cur
31+ }
32+ if ( i === n ) {
33+ sliceEnd = cur
34+ }
35+ cur = cur . next
36+ i ++
37+ }
38+
39+ let sliceEndNext = sliceEnd . next
40+ // 切断切分终点的next 防止反转的时候反转过头
41+ sliceEnd . next = null
42+
43+ const { head : slicedHead , tail : slicedTail } = reverse ( sliceStart )
44+ if ( sliceStartPrev ) {
45+ // 如果需要反转的部分有前一个节点 那么只需要在中间动手脚 原样返回head节点即可
46+ sliceStartPrev . next = slicedHead
47+ } else {
48+ // 这里需要注意的是 如果没有sliceStartPrev 说明是从第一个节点就开始反转的
49+ // 那么我们需要手动调整head为反转后的head
50+ head = slicedHead
51+ }
52+ slicedTail . next = sliceEndNext
53+
54+ return head
55+ }
56+
57+ function reverse ( head ) {
58+ let prev = null
59+ let cur = head
60+ while ( cur ) {
61+ let next = cur . next
62+ cur . next = prev
63+
64+ prev = cur
65+ cur = next
66+ }
67+ // 返回反转后的头尾节点
68+ return { head : prev , tail : head }
69+ }
70+
71+ let node = new ListNode ( 3 )
72+ node . next = new ListNode ( 5 )
73+
74+ console . log ( JSON . stringify ( reverseBetween ( node , 1 , 1 ) ) )
You can’t perform that action at this time.
0 commit comments