アルゴリズムとデータ構造面接問題(10)-チェーンテーブルを逆転


タイトル
                。               。

問題を解く構想.
1.再帰逆さにする
2.逆さまにしないようにする
コード#コード#
1.再帰式
public class Problem8 {

	public LinkedListNode invert(LinkedListNode node) {
		if (node == null) {
			throw new NullPointerException();
		}

		LinkedListNode endNode = null;
		LinkedListNode nextNode = node.getNextNode();
		if (nextNode != null) {
			node.setNextNode(null);
			endNode = invert(nextNode);
			nextNode.setNextNode(node);
		} else {
			endNode = node;
		}

		return endNode;
	}

	public LinkedListNode parseLinkedList(int[] data) {
		LinkedListNode lastNode = null;
		for (int i = data.length - 1; i >= 0; i--) {
			LinkedListNode currentNode = new LinkedListNode();
			currentNode.setValue(data[i]);
			currentNode.setNextNode(lastNode);
			lastNode = currentNode;
		}

		return lastNode;
	}

	public static void main(String[] args) {
		int[] data = { 1, 2, 3, 4, 5, 6, 7 };
		Problem8 problem8 = new Problem8();
		LinkedListNode rootNode = problem8.parseLinkedList(data);
		LinkedListNode endNode = problem8.invert(rootNode);
		problem8.printlnLinkedArray(endNode);
		System.out.println("Done");
	}
	public void printlnLinkedArray(LinkedListNode node){
		if(node == null) return;
		System.out.println("" + node.getValue());
		printlnLinkedArray(node.getNextNode());
	}
}

しゅつりょく
7
6
5
4
3
2
1
Done

2.非再帰式
public class Problem8_2 {
	public LinkedListNode invert(LinkedListNode node, int length) {
		LinkedListNode[] nodes = new LinkedListNode[length];
		//    
		for (int i = 0; i < length; i++) {
			if (node != null) {
				nodes[i] = node;
				node = node.getNextNode();
			}
		}
		//      

		for (int i = length - 1; i >= 0; i--) {
			if (i == 0) {
				nodes[i].setNextNode(null);
			} else {
				nodes[i].setNextNode(nodes[i - 1]);
			}
		}

		return nodes[length - 1];
	}

	public LinkedListNode parseLinkedList(int[] data) {
		LinkedListNode lastNode = null;
		for (int i = data.length - 1; i >= 0; i--) {
			LinkedListNode currentNode = new LinkedListNode();
			currentNode.setValue(data[i]);
			currentNode.setNextNode(lastNode);
			lastNode = currentNode;
		}

		return lastNode;
	}

	public static void main(String[] args) {
		int[] data = { 1, 2, 3, 4, 5, 6, 7 };
		Problem8_2 problem8 = new Problem8_2();
		LinkedListNode rootNode = problem8.parseLinkedList(data);
		LinkedListNode endNode = problem8.invert(rootNode, data.length);
		problem8.printlnLinkedArray(endNode);
		System.out.println("Done");
	}

	public void printlnLinkedArray(LinkedListNode node) {
		if (node == null)
			return;
		System.out.println("" + node.getValue());
		printlnLinkedArray(node.getNextNode());
	}

}