1、题目
按照步长k翻转单链表,如1->2->3->4->5,翻转2步为,2->1->3->4->5。
2、思路:
1、同翻转链表一致,边遍历链表,边翻转;只是需要继续新链表已经翻转的长度,到达k时,不再翻转
2、维护新链表的尾部元素指针
代码:
package com.datastructure.link;
/**
* 按照k步反转链表
* 如:1->2->3->4->5
* 翻转3步为3->2->1->4->5
*
*
*/
public class ReverseLinkByK {
static class Node {
int value;
Node next;
Node(int value) {
this.value = value;
}
@Override
public String toString() {
if (this.next == null) {
return String.valueOf(this.value);
}
return this.value + "->" + this.next.toString();
}
}
public static Node reverseLinkByKStep(Node head, int k) {
if (head == null || k <= 1) {
return head;
}
Node newNode = null;
Node newTail = null;
Node curNode = head;
int count = 0;
while (curNode != null) {
count++;
// 缓存下一个元素
Node nextNode = curNode.next;
// 翻转元素
curNode.next = newNode;
// 推进新链表头节点
newNode = curNode;
// 到达k次 则遍历出当前的尾节点,指向下一个元素
/*
if (count == k) {
Node tmp = newNode;
while (tmp.next != null) {
tmp = tmp.next;
}
tmp.next = nextNode;
break;
}
*/
// 也可把尾节点缓存下来
if (count == 1) {
newTail = curNode;
}
if (count == k) {
newTail.next = nextNode;
break;
}
// 推进当前节点
curNode = nextNode;
}
return newNode;
}
public static void main(String[] args) {
Node node = createTestLinkedList();
System.out.println(node);
System.out.println(reverseLinkByKStep(node, 3));
}
private static Node createTestLinkedList() {
Node head = new Node(0);
Node curNode = head;
for (int i = 1; i < 10; i++) {
curNode.next = new Node(i);
curNode = curNode.next;
}
return head;
}
}