Untitled
unknown
java
a year ago
1.5 kB
13
Indexable
public class Solution { public boolean checkRemainingNodes(ListNode head,int k) { ListNode tempNode=head; int count=0; while(tempNode.next!=null) { tempNode=tempNode.next; count++; } if(count>=k) return true; return false; } public ListNode getKthNode(ListNode head, int k) { ListNode tempNode=head; for(int i=0;i<k-1;i++) { tempNode=tempNode.next; } return tempNode; } public ListNode reverse(ListNode head) { ListNode prev=null; ListNode curr=head; while(curr!=null) { ListNode nextNode=curr.next; curr.next=prev; prev=curr; curr=nextNode; if(nextNode!=null) { nextNode=nextNode.next; } } return prev; } public void displayList(ListNode head) { ListNode tempNode=head; while(tempNode!=null) { System.out.print(tempNode.val+" "); tempNode=tempNode.next; } } public ListNode reverseKGroup(ListNode head, int k) { //You can code here ListNode dummyHead= new ListNode(0); dummyHead.next=head; ListNode point=dummyHead; while(checkRemainingNodes(point,k)){ ListNode start=point.next; ListNode end = getKthNode(start,k); ListNode nextNode=end.next; end.next=null; point.next=reverse(start); displayList(point.next); start.next=nextNode; point=start; } return dummyHead.next; } }
Editor is loading...
Leave a Comment