/**
* Given a linked list, reverse the nodes of a linked list k at a time and
* return its modified list.
*
* k is a positive integer and is less than or equal to the length of the linked
* list. 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
*
* @difficulty hard
* @author
* @date
* @copyright
*/
public class ReverseNodesInKGroupImpl implements ReverseNodesInKGroup {
@Override
public ListNode reverseKGroup(ListNode head, int k) {
if (head == null || head.getNext() == null) {
return head;
}
ListNode tailNode = head;
ListNode tmp = null;
ListNode headNode = head;
int i = 1;
while (tailNode != null) {
tailNode = tailNode.getNext();
i++;
if (i == k && tailNode != null) {
tmp = tailNode.getNext(); //下次reverse的头.
tailNode.setNext(null); //本次reverse的结束符.
break;
}
}
ListNode result;
if (i == k && tailNode != null) {
result = reverse(headNode);
headNode.setNext(reverseKGroup(tmp, k)); //headNode为本次reverse的尾,接到下次reverse的头.
} else {
result = head;
}
return result;
}
/*
* 递归反转单链表.
*/
public ListNode reverse(ListNode head) {
if (head == null || head.getNext() == null) {
return head;
}
ListNode newHead = reverse(head.getNext());
head.getNext().setNext(head);
head.setNext(null);
return newHead;
}
}
LeeCode刷题之ReverseNodesInKGroup, JAVA实现
最新推荐文章于 2023-12-08 15:16:16 发布