【发布时间】:2014-03-22 21:00:18
【问题描述】:
我已经实现了一个 java 代码,它反转链表中的每个 k 节点,代码如下:
public class ReverseALinkedList {
public static void main(String[] args) {
int k = 2;
Node a = new Node(1);
Node b = new Node(2);
Node c = new Node(3);
Node d = new Node(4);
Node e = new Node(5);
Node f = new Node(6);
Node g = new Node(7);
Node h = new Node(8);
a.next = b;
b.next = c;
c.next = d;
d.next = e;
e.next = f;
f.next = g;
g.next = h;
a.printLinkedList();
Node head = reverseKLinkedList(a, k);
head.printLinkedList();
}
private static Node reverseKLinkedList(Node first, int k) {
Node current;
Node temp;
int count = 0;
current = null;
while (first != null && count < k) {
temp = first.next;
first.next = current;
current = first;
first = temp;
++count;
}
if (first != null) {
first.next = reverseKLinkedList(first, k);
}
return current;
}
static class Node {
public Node next;
public int value;
public Node(int value) {
this.value = value;
}
public void printLinkedList() {
Node head = this;
while (head.next != null) {
System.out.print(head.value + "->");
head = head.next;
}
System.out.print(head.value + "->null");
System.out.println();
}
}
}
当我使用以下链表执行代码时:
1->2->3->4->5->6->null 和 k 设置为 2,我得到如下输出:
2->1->空
其余节点被反转(即 4->3、6->5),但在递归调用期间不会返回它们。
谁能告诉我如何解决这个问题?
【问题讨论】:
-
我不明白哪个是您想要的输出。
-
期望的输出应该是:2->1->4->3->6->5->null
-
如果
k==3,期望的输出是什么?会是 1->3->2->4->6->5->null 吗?还是 3->2->1->6->5->4->null? -
@JimMischel 你完全正确!
-
我为输出提供了两个选项。是哪一个?
标签: java data-structures linked-list