If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For example,
Given this linked list:
1->2->3->4->5
For k = 2, you should return:
2->1->4->3->5
For k = 3, you should return:
3->2->1->4->5
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode reverseKGroup(ListNode head, int k) { // O(1, pre) -> O(2, last) -> O(3, cur) -> O(4) -> O(5) -> O(6) // Changed to O(1, pre) -> O(3) -> O(2, last) -> O(4, cur) -> O(5) -> O(6) // Move cur node after pre, then new cur node is the if (head==null || head.next==null) return head; if (k <= 1) return head; ListNode helper = new ListNode(0); helper.next = head; ListNode pre = helper; // Firstly, get the length of the list int len = 0; for (ListNode node = head; node != null; node = node.next) len++; int cnt = len / k; // Number of reverse for (int i = 0; i < cnt; i++) pre = reverse(pre, k); return helper.next; } private ListNode reverse(ListNode pre, int k) { ListNode last = pre.next; ListNode cur = last.next; int count = 0; while (count < k-1) { last.next = cur.next; cur.next = pre.next; pre.next = cur; cur = last.next; count++; } return last; } }
No comments:
Post a Comment