File tree 1 file changed +34
-12
lines changed
1 file changed +34
-12
lines changed Original file line number Diff line number Diff line change 10
10
*/
11
11
class Solution {
12
12
public ListNode swapNodes (ListNode head , int k ) {
13
- ListNode fast = null ;
13
+ int listLength = 0 ;
14
14
ListNode curr = head ;
15
- int currCount = 1 ;
16
- while ( currCount != k ) {
15
+ while ( curr != null ) {
16
+ listLength ++;
17
17
curr = curr .next ;
18
- currCount ++;
19
18
}
20
- fast = curr ;
21
- ListNode slow = head ;
22
- while (curr .next != null ) {
23
- slow = slow .next ;
24
- curr = curr .next ;
19
+ ListNode startPrev = null ;
20
+ ListNode start = head ;
21
+ ListNode endPrev = null ;
22
+ ListNode end = head ;
23
+ int count = k - 1 ;
24
+ while (count > 0 ) {
25
+ startPrev = start ;
26
+ start = start .next ;
27
+ count --;
28
+ }
29
+ count = listLength - k ;
30
+ while (count > 0 ) {
31
+ endPrev = end ;
32
+ end = end .next ;
33
+ count --;
34
+ }
35
+ if (startPrev != null ) {
36
+ startPrev .next = end ;
37
+ }
38
+ if (endPrev != null ) {
39
+ endPrev .next = start ;
40
+ }
41
+ ListNode temp = start .next ;
42
+ start .next = end .next ;
43
+ end .next = temp ;
44
+ // Updating head pointers if required
45
+ if (k == 1 ) {
46
+ head = end ;
47
+ }
48
+ if (k == listLength ) {
49
+ head = start ;
25
50
}
26
- int temp = fast .val ;
27
- fast .val = slow .val ;
28
- slow .val = temp ;
29
51
return head ;
30
52
}
31
53
}
You can’t perform that action at this time.
0 commit comments