Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Definition for singly-linked list.
- * public class ListNode {
- * int val;
- * ListNode next;
- * ListNode() {}
- * ListNode(int val) { this.val = val; }
- * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
- * }
- */
- class Solution {
- public ListNode reverseKGroup(ListNode head, int k) {
- ListNode resHead = null;
- ListNode cur = head;
- int totalNodes = 0;
- while (cur != null) {
- cur = cur.next;
- totalNodes++;
- }
- cur = head;
- ListNode prevTail = null;
- int pNodes = 0;
- while (cur != null) {
- int ck = k;
- ListNode curTail = cur;
- ListNode prev = null;
- while (ck > 0 && cur != null) {
- pNodes++;
- ListNode next = cur.next;
- cur.next = prev;
- prev=cur;
- cur = next;
- ck--;
- }
- ListNode curHead = prev;
- if (resHead == null) {
- resHead = curHead;
- }
- ListNode cr = curHead;
- while (cr!=null){
- System.out.println(cr.val);
- cr=cr.next;
- }
- // System.out.println("-----");
- if (prevTail != null) {
- prevTail.next = prev;
- prevTail = curTail;
- prevTail.next = null;
- }
- if (prevTail == null) {
- prevTail = curTail;
- }
- if (totalNodes - pNodes < k) {
- prevTail.next = cur;
- return resHead;
- }
- }
- return resHead;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement