您的位置:首页 > 理论基础 > 数据结构算法

算法与数据结构面试题(10)-颠倒链表

2014-12-19 11:15 309 查看

题目

用一种算法来颠倒一个链接表的顺序。现在在不用递归式的情况下做一遍。

解题思路

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());
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐