给定链表与数字K,根据每个节点的位置,对K取余,根据模后的值从小到大重组链表,同余数值的节点保持元素节点相对位置不变。
要求只遍历一次链表
输入:
0-1->2->3->4
k=2
输出:
0->2->4->1->3
输入:
0-1->2->3->4->5->6->7
k=3
输出:
0->3->6->1->4->7->2->5
public class Test15 {
//0,1,2,3,4,5,6,7
//k=3
// {
// 0:0
// 1:1
// 2:2
// }
//0,3,6,1,4,7,2,5
static class Node {
int val;
Node next;
public Node(int val) {
this.val = val;
}
public Node(int val, Node next) {
this.val = val;
this.next = next;
}
}
public static Node newLink(Node head, int k) {
Map<Integer, Node> hashMap = new HashMap<>();
Node tmp = head;
int loc = 0;
while (tmp != null) {
Node next = tmp.next;
int key = loc % k;
Node tNode = hashMap.get(key);
if (tNode == null) {
hashMap.put(key, tmp);
} else {
//将上一个数的next节点赋予给当前数的next域,用于记录链式关系,避免二次循环遍历
Node preNext = tNode.next;
tNode.next = tmp;
tmp.next = preNext;
hashMap.put(key, tmp);
}
loc++;
tmp = next;
}
//最后一位next指针置空,防止死循环
Node tail = hashMap.get(k - 1);
if (tail != null) {
tail.next = null;
}
return head;
}
public static void main(String[] args) {
Node n7 = new Node(7);
Node n6 = new Node(6, n7);
Node n5 = new Node(5, n6);
Node n4 = new Node(4, n5);
Node n3 = new Node(3, n4);
Node n2 = new Node(2, n3);
Node n1 = new Node(1, n2);
Node n0 = new Node(0, n1);
Node node = newLink(n0, 3);
while (node != null) {
System.out.print(node.val + " ");
node = node.next;
}
}
}