问题描述
给定一个单链表的头节点 head,实现一个调整单链表的函数,使得每K个节点之间为一组进行逆序,并且从链表的尾部开始组起,头部剩余节点数量不够一组的不需要逆序。(不能使用队列或者栈作为辅助)
例如:链表:1->2->3->4->5->6->7->8->null, K = 3。那么 6->7->8,3->4->5,1->2各位一组。调整后:1->2->5->4->3->8->7->6->null。其中 1,2不调整,因为不够一组。
解法详情
public class ListNode {
ListNode next;
int value;
public ListNode(int value) {
this.value = value;
}
@Override
public String toString() {
String str = this.value +"->";
str += this.next == null ? "null" : this.next;
return str;
}
}
public class TestNode {
public static void main(String[] args) {
TestNode testNode = new TestNode();
int n = 8;
int k = 3;
ListNode oldNodeHead = new ListNode(0);
ListNode temp = oldNodeHead;///初始化链表
for (int i = 1; i <= n; i++) {
temp.next = new ListNode(i);
temp = temp.next;
}
System.out.println(oldNodeHead.next);
System.out.println(testNode.createReverseNode(n, k, oldNodeHead));
}
public ListNode createReverseNode(int n, int k, ListNode oldNodeHead) {
int size = n % k == 0 ? n / k : n / k + 1;
boolean lastSort = n % k != 0 ? true : false;
ListNode[] listNodes = new ListNode[size];//分组的数组
oldNodeHead = this.reverseOrder(oldNodeHead.next);
int index = 0;
int position = 0;
ListNode tempHead = null;
while (oldNodeHead != null) {
if (position % k == 0) {
listNodes[index] = new ListNode(oldNodeHead.value);//创建头节点
tempHead = listNodes[index];
index++;
} else {
if (tempHead != null) {
tempHead.next = new ListNode(oldNodeHead.value);
tempHead = tempHead.next;
}
}
oldNodeHead = oldNodeHead.next;
position++;
}
sortArray(listNodes, lastSort);
return this.reverseOrder(createNewListNode(listNodes));
}
/**
* 链表数组组装成一个新的链表
*/
private ListNode createNewListNode(ListNode[] listNodes) {
ListNode head = new ListNode(0);
ListNode temp = head;
for (ListNode listNode : listNodes) {
temp.next = listNode;
while (temp.next != null) temp = temp.next;
}
return head.next;
}
/**
* 逆序整个数组
*/
private void sortArray(ListNode[] listNodes, boolean flag) {
for (int i = 0; i < listNodes.length; i++) {
if (flag && i == listNodes.length - 1) {
continue;
}
listNodes[i] = reverseOrder(listNodes[i]);
}
}
/**
* 逆序单链表
*/
private ListNode reverseOrder(ListNode listNode) {
if (listNode.next == null) {
return listNode;
}
ListNode head = new ListNode(0);
while (listNode != null) {
ListNode temp = head.next;
head.next = new ListNode(listNode.value);
head.next.next = temp;
listNode = listNode.next;
}
return head.next;
}
}
输入输出结果