链表的翻转是程序员面试中出现频度最高的问题之一,常见的解决方法分为递归和迭代两种。迭代是从前往后依次处理,直到循环到链尾;而递归恰恰相反,首先一直迭代到链尾也就是递归基判断的准则,然后再逐层返回处理到开头。总结来说,链表翻转操作的顺序对于迭代来说是从链头往链尾,而对于递归是从链尾往链头。
以下为具体的实现代码:
定义结点:
/*** 定义节点* @param */
class Node{
T data;
Node next;
public Node(T data) {
this.data = data;
}
public Node(T data, Node next) {
this.data = data;
this.next = next;
}
}
迭代实现:
/**
* 迭代实现方法
* @param node
* @return
*/
public static Node reverseLinkedListOne(Node node){
Node previousNode = null;
Node currentNode = node;
while (currentNode != null){
Node next = currentNode.next;
currentNode.next = previousNode;
previousNode = currentNode;
currentNode = next;
}
return previousNode;
}
递归实现:
/**
* 递归方式
* @param node
* @return
*/
public static Node reverseLinkedListTwo(Node node){
if(node == null || node.next == null){
return node;
}
Node newNode = reverseLinkedListTwo(node.next);
node.next.next = node;
node.next = null;
return newNode;
}
测试方法:
public static void main(String[] args) {
Node linkNode1 = new Node(1);
Node linkNode2 = new Node(2);
Node linkNode3 = new Node(3);
Node linkNode4 = new Node(4);
Node linkNode5 = new Node(5);
Node linkNode6 = new Node(6);
linkNode1.next = linkNode2;
linkNode2.next = linkNode3;
linkNode3.next = linkNode4;
linkNode4.next = linkNode5;
linkNode5.next = linkNode6;
Node node1 =reverseLinkedListOne(linkNode1);
while (node1!= null){
System.out.println(node1.data);
node1 = node1.next;
}
System.out.println("--------------------------------");
Node node2 =reverseLinkedListTwo(linkNode1);
while (node2 != null){
System.out.println(node2.data);
node2 = node2.next;
}
}
测试结果:
6
5
4
3
2
1