File tree Expand file tree Collapse file tree 1 file changed +69
-0
lines changed
Leetcode/leetcodeTags/LinkedList Expand file tree Collapse file tree 1 file changed +69
-0
lines changed Original file line number Diff line number Diff line change 1+ package LinkedList ;
2+
3+ public class ReverseNodesInK_Group25 {
4+
5+ public class ListNode {
6+ int val ;
7+ ListNode next ;
8+
9+ ListNode () {
10+ }
11+
12+ ListNode (int val ) {
13+ this .val = val ;
14+ }
15+
16+ ListNode (int val , ListNode next ) {
17+ this .val = val ;
18+ this .next = next ;
19+ }
20+ }
21+
22+ // time: O(n), space: O(n/k)
23+ public ListNode reverseKGroup (ListNode head , int k ) {
24+ if (head == null || head .next == null || k == 1 )
25+ return head ;
26+
27+ ListNode start = head ;
28+ ListNode end = head ;
29+ int moveEndCursor = k - 1 ;
30+
31+ while (moveEndCursor != 0 ) {
32+ end = end .next ;
33+ moveEndCursor --;
34+
35+ if (end == null )
36+ return head ;
37+ }
38+
39+ ListNode newHead = reverseKGroup (end .next , k );
40+
41+ reverseIterative (start , end );
42+
43+ start .next = newHead ;
44+
45+ return end ;
46+ }
47+
48+ private void reverseIterative (ListNode start , ListNode end ) {
49+
50+ ListNode prev = null ;
51+ ListNode curr = start ;
52+ ListNode nxt = start .next ;
53+
54+ while (prev != end ) {
55+ curr .next = prev ;
56+ prev = curr ;
57+ curr = nxt ;
58+
59+ if (nxt != null )
60+ nxt = nxt .next ;
61+ }
62+ }
63+
64+ // 2nd approach
65+ public ListNode reverseKGroupSpaceEfficient (ListNode head , int k ) {
66+ f
67+ }
68+
69+ }
You can’t perform that action at this time.
0 commit comments