File tree 1 file changed +57
-0
lines changed
1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Definition for singly-linked list.
3
+ * public class ListNode {
4
+ * int val;
5
+ * ListNode next;
6
+ * ListNode() {}
7
+ * ListNode(int val) { this.val = val; }
8
+ * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
9
+ * }
10
+ */
11
+ class Solution {
12
+ public ListNode reverseEvenLengthGroups (ListNode head ) {
13
+ if (head == null ) {
14
+ return head ;
15
+ }
16
+ int numOfNodes = 1 ;
17
+ ListNode prev = null ;
18
+ ListNode curr = head ;
19
+ int totalNumOfNodes = 0 ;
20
+ while (curr != null ) {
21
+ totalNumOfNodes ++;
22
+ curr = curr .next ;
23
+ }
24
+ curr = head ;
25
+ while (curr != null ) {
26
+ numOfNodes = Math .min (numOfNodes , totalNumOfNodes );
27
+ totalNumOfNodes -= numOfNodes ;
28
+ if (numOfNodes % 2 == 0 ) {
29
+ ListNode [] res = reverseList (curr , numOfNodes );
30
+ prev .next = res [0 ];
31
+ prev = curr ;
32
+ curr = res [1 ];
33
+ } else {
34
+ for (int i = 0 ; i < numOfNodes && curr != null ; i ++) {
35
+ prev = curr ;
36
+ curr = curr .next ;
37
+ }
38
+ }
39
+ numOfNodes ++;
40
+ }
41
+ return head ;
42
+ }
43
+
44
+ private ListNode [] reverseList (ListNode node , int n ) {
45
+ ListNode prev = null ;
46
+ ListNode curr = node ;
47
+ ListNode post = null ;
48
+ while (n -- > 0 ) {
49
+ post = curr .next ;
50
+ curr .next = prev ;
51
+ prev = curr ;
52
+ curr = post ;
53
+ }
54
+ node .next = curr ;
55
+ return new ListNode []{prev , post };
56
+ }
57
+ }
You can’t perform that action at this time.
0 commit comments