题意:啥意思,一听就懵,那么是这样的,给你一个链表,再给你一个整数,你就在这条链表上面数,数到k个节点,就把这几个节点反转 比如:
链表:1->2->3->5->7->8->4->98 k=3
调整后:3->2->1->8->7->5->4->98
/**
* K个节点的组内逆序调整
*/
public class Code05 {
public static class Node<V> {
public V value;
public Node<V> last;
public Node<V> next;
public Node() {
}
public Node(V v) {
value = v;
last = null;
next = null;
}
}
//找出当前要反转的组的结尾位置
public static Node getGroupEnd(Node head,int k){
Node end = head;
if(end==null){
return null;
}
k--;
while (k>0){
if(end==null){
return null;
}
end = end.next;
k--;
}
return end;
}
public static Node reverseK(Node head1,int K){
Node lastEnd = head1;
Node newHead = null;
//第一组拿到的end就等于新的头部,最后返回的就是它
newHead = getGroupEnd(lastEnd,K);
//如果不满足K个,直接返回
if(newHead == null){
return lastEnd;
}
//先记下 下一组开始的位置
Node nextStart = newHead.next;
//将结尾的下一个节点清空,便于反转
Node end = newHead;
end.next=null;
reverse(lastEnd);
while (true){
// 找end的位置
end = getGroupEnd(nextStart,K);
//不满足K
if (end==null){
//将上一个结尾的位置指向后面剩下的节点,head本身是原来的头部,但是现在变成了第一组的尾部
lastEnd.next = nextStart;
//直接返回新的头部
return newHead;
}
//记下当前组的开头位置
Node cur = nextStart;
//将nextStart记为下一组的开头
nextStart = end.next;
//清空当前尾节点的下一个指向,便于反转
end.next = null;
//组内反转
Node tmpHead = reverse(cur);
//上一个尾节点的下一个,指向当前组的新头部
lastEnd.next = tmpHead;
lastEnd = cur;
}
}
// 组内逆序
public static Node reverse(Node head){
Node pre = null;
Node next = null;
while (head != null){
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
public static void print(Node head){
while (head != null){
System.out.print(head.value+" ");
head = head.next;
}
}
public static void main(String[] args) {
Node node1 = new Node(1);
Node node2 = new Node(2);
Node node3 = new Node(3);
Node node4 = new Node(4);
Node node5 = new Node(5);
Node node6 = new Node(6);
Node node7 = new Node(7);
Node node8 = new Node(8);
node1.next=node2;
node2.next=node3;
node3.next = node4;
node4.next = node5;
node5.next = node6;
node6.next = node7;
node7.next = node8;
Node ret = reverseK(node1,3);
print(ret);
}
}