public class ListReverse {
public static void main(String[] args){
Node d = new Node("d", null);
Node c = new Node("c", d);
Node b = new Node("b", c);
Node a = new Node("a", b);
Node head = a;
System.out.print("排序前:");
while(head != null){
System.out.print(head.getData() + " ");
head = head.getNext();
}
//head = resverse1(a);
head = resverse2(a);
System.out.print("\n" + "排序后:");
while(head != null){
System.out.print(head.getData() + " ");
head = head.getNext();
}
}
/*
* 递归实现
* 从后向前修改指针指向
*/
private static Node resverse1(Node head) {
if (head == null || head.getNext() == null) {
return head;
}
Node reHead = resverse1(head.getNext());// 先反转后续节点head.getNext()
head.getNext().setNext(head);// 将当前结点的指针域指向前一结点
head.setNext(null);// 前一结点的指针域令为null;
return reHead;// 反转后新链表的头结点node
}
/*
* 非递归实现
* 从前向后修改指针指向
*/
private static Node resverse2(Node head) {
if(head == null) {
return head;
}
Node pre = null;
Node cur = head;
Node temp = null;
while (cur != null) {
temp = cur.getNext();
cur.setNext(pre);
pre = cur;
cur = temp;
}
return pre;
}
} this
class Node{
private String data;
private Node next;
public Node(String data){
this.data = data;
}
public Node(String data, Node next){
this.data = data;
this.next = next;
}
public void setNext(Node node){
this.next = node;
}
public Node getNext(){
return next;
}
public void setData(String data){
this.data = data;
}
public String getData(){
return data;
}
}.net
//递归实现参考 http://blog.csdn.net/guyuealian/article/details/51119499指针