参考博客:
http://blog.csdn.net/beiyetengqing/article/details/7596554
非递归算法:
a---->b---->c---->d
a != null ; b != null;
next = b; next = c;
a.next = null; b.next = a;
pre = a; pre = b;
current = b current = c; ...
/**
* 非递归算法
*/
public static Node reverseNonRecursion(Node current) {
if (null == current) {
return current;
}
Node previousNode = null;
Node next = null;
while (null != current) {
next = current.getNext();
current.setNext(previousNode);
previousNode = current;
current = next;
}
return previousNode;
}
递归算法:
a---->b---->c
*************************
对象438
nextNode = b;
a.next = null;
rR = reverseRecursion(b);
*************************
对象439
nextNode = c;
b.next = null;
rR = reverseRecursion(c);
*************************
对象440
return c;
*************************
c.next = b;
b.next = a;
*************************
/**
* 递归,在反转当前节点之前先反转后续节点
*/
public static Node reverseRecursion(Node current) {
if (current == null || current.getNext() == null) return current;
Node nextNode = current.getNext();
current.setNext(null);
Node reverseRest = reverseRecursion(nextNode);
nextNode.setNext(current);
return reverseRest;
}
完整程序
/**
* 定义一个单链表
*/
class Node {
//变量
private int data;
//指向下一个对象
private Node next;
public Node(int data) {
this.data = data;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
/**
*
* 两种方式实现单链表的反转(递归、普通)
*/
public class ReverseSingleList {
/**
* 递归,在反转当前节点之前先反转后续节点
*/
public static Node reverseRecursion(Node current) {
if (current == null || current.getNext() == null) return current;
Node nextNode = current.getNext();
current.setNext(null);
Node reverseRest = reverseRecursion(nextNode);
nextNode.setNext(current);
return reverseRest;
}
/**
* 遍历,将当前节点的下一个节点缓存后更改当前节点指针
*
*/
public static Node reverseNonRecursion(Node current) {
if (null == current) {
return current;
}
Node previousNode = null;
Node next = null;
while (null != current) {
next = current.getNext();
current.setNext(previousNode);
previousNode = current;
current = next;
}
return previousNode;
}
public static void main(String[] args) {
Node current = new Node(0);
Node tmp = null;
Node cur = null;
// 构造一个长度为10的链表,保存头节点对象current
for (int i = 1; i < 10; i++) {
tmp = new Node(i);
if (1 == i) {
current.setNext(tmp);
} else {
cur.setNext(tmp);
}
cur = tmp;
}
//打印反转前的链表
Node h = current;
while (null != h) {
System.out.print(h.getData() + " ");
h = h.getNext();
}
//调用反转方法
//current = reverseNonRecursion(current);
current = reverseRecursion(current);
System.out.println("\n**************************");
//打印反转后的结果
while (null != current) {
System.out.print(current.getData() + " ");
current = current.getNext();
}
}
}
执行结果:
0 1 2 3 4 5 6 7 8 9
**************************
9 8 7 6 5 4 3 2 1 0