将链表以m长度为一组反转链表
一群友分享的阿里面试题
1.将head链表以m为组反转链表(不足m则不反转):
例子:假设m=3. 链表 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 ->8
output: 3 -> 2 -> 1 ->6 ->5 ->4 -> 7 ->8
解法一:使用JDK的链表LinkedList
没有体现出链表的链式处理方式
代码
public static void main(String[] args) {
Integer[] array = new Integer[]{1, 2, 3, 4, 5, 6, 7, 8};
LinkedList<Integer> linkedList = new LinkedList();
linkedList.addAll(Arrays.asList(array));
int m = 3;
System.out.println("当 m = " + m);
System.out.println("before handler");
for (Integer integer : linkedList) {
System.out.print(integer + " ");
}
System.out.println();
//核心代码处
for (int i = 0; i < linkedList.size(); i++) {
if (i % m == m - 1) {
int start = i - m + 1;
int end = i;
for (int a = 0; a < m / 2; a++) {
Integer temp = linkedList.get(start + a);
linkedList.set(start + a, linkedList.get(end - a));
linkedList.set(end - a, temp);
}
}
}
System.out.println("after handler");
for (Integer integer : linkedList) {
System.out.print(integer + " ");
}
}
运行效果:
当 m = 3
before handler
1 2 3 4 5 6 7 8
after handler
3 2 1 6 5 4 7 8
解法二:自己构造链表,用链的方式遍历处理链表
创建链表作为一个类使用
class Node<T> {
T value;
Node<T> next;
}
遍历链表
public static <T> void printLink(Node<T> head) {
Node<T> node = head;
while (node != null) {
System.out.print(node.value + " ");
node = node.next;
}
System.out.println();
}
将数组转换成链表,并返回链表head
/**
* 将数组转成链表
*
* @param array
* @param T类型的数组
* @return Node<T>类型的链表head
*/
public static <T> Node<T> arrayToNodeList(T[] array) {
Node<T> node = new Node<T>();
Node<T> head = node;
for (T object : array) {
Node<T> temp = new Node<T>();
temp.value = object;
node.next = temp;
node = temp;
}
head = head.next;
return head;
}
递归分组反转链表
/**
* @param head 需要反转的头结点,
* @param m 以m为一组反转
* @return 返回以m为一组反转完成的链表
*/
public static <T>Node<T> linkReverse(Node<T> head, int m) {
if (head == null || head.next == null) {
return head;
}
int count = 0;
Node<T> current = head;
while (count != m && current != null) {
current = current.next;
count++;
}
if (count == m) {
current = linkReverse(current, m);
while (count-- > 0) {
Node<T> temp = head.next;
head.next = current;
current = head;
head = temp;
}
head = current;
}
return head;
}
实例测试
public static void main(String[] args) {
Integer[] array = new Integer[]{1, 2, 3, 4, 5, 6, 7, 8};
//构造单向链表
Node<Integer> head = arrayToNodeList(array);
System.out.println("before handler");
printLink(head);
System.out.println("after handler");
printLink(linkReverse(head, 3));
}
结果输出
before handler
1 2 3 4 5 6 7 8
after handler
3 2 1 6 5 4 7 8