题解 | #链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
http://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
public ListNode reverseKGroup (ListNode head, int k) {
if (head == null || k < 0) {
return head;
}
int len = 0;
ListNode temp = head;
while (temp != null) {
len++;
temp = temp.next;
}
ListNode headNode = new ListNode(-1);
headNode.next = head;
ListNode tempHeadNode = headNode;
ListNode curNode = head;
ListNode nextNode = null;
for (int i = 0; i < len/k; i++) {
for (int j = 1; j < k; j++) {
nextNode = curNode.next;
curNode.next = nextNode.next;
nextNode.next = tempHeadNode.next;
tempHeadNode.next = nextNode;
}
tempHeadNode = curNode;
//这样写 也可以curNode = headTempNode.next;
curNode = curNode.next;
}
return headNode.next;
}
}
360集团公司福利 401人发布